Friday, November 27, 2009

ASP.NET Validation Controls - Conditionally validating

Using the server side Page.Validate() and Client Side Page_ClientValidate() , we can validate a group of controls conditionally. For eg. i just need to validate some fields only when a checkbox is checked. Both Page.Validate() and Page_ClientValidate() allows to pass a validation group , So we group a set of controls with a validation group and calls this validation functions in both client & server side only on the required validation condition

Server Side

protected void btnSubmit_Click(object sender, EventArgs e)
if (!IsValid) return;
lblMsg.Text = "Passed validation";


function CheckValidation() {
var cbValidate = document.getElementById('<%=cbValidate.ClientID %>');
var flag = true;
if (cbValidate.checked) {
if (!Page_ClientValidate("vgSubmit"))
flag = false;
else {
return flag;


Download Code

Wednesday, September 23, 2009

URL Rewriting with ASP.NET 3.5 using System.Web.Routing.UrlRoutingModule

In 2.0 we used Context.RewritePath() or other URL rewrite modules. With 3.5 its easy to do. I did it for my blog for better SEO.

      • Add reference to system.Web.Routing
        Add System.Web.Routing.UrlRoutingModule http module to web.config
        Implement an IRouteHandler
        Registering routes in global.asax

I am going to rewrite blogs/Posts/{BlogPostID}/{*BlogPostTitle}

I implemented a generic IRouteHandler , it will copy url parameters( eg: BlogPostID,BlogPostTitle ) to http context item collection, so i can URL rewrite any page , without modifying IRouteHandler implementation.

using System;
using System.Web;
using System.Web.Routing;
using System.Web.Compilation;
using System.Web.UI;
public class SiteRouteHandler : IRouteHandler
//30 june 2009 Priyan R

public IHttpHandler GetHttpHandler(RequestContext requestContext)
Page page;
page = BuildManager.CreateInstanceFromVirtualPath(PageVirtualPath, typeof(Page)) as Page;
foreach (var item in requestContext.RouteData.Values)
HttpContext.Current.Items["qparam." + item.Key] = item.Value;
return page;
public string PageVirtualPath { get; set; }

In global.asax added


new Route("Blogs/Posts/{BlogPostID}/{*BlogPostTitle}",
new SiteRouteHandler() { PageVirtualPath = "~/Blogs/Details.aspx" })

So in Details.aspx I can read the parameters


Check the code.

Download Code

Wednesday, August 12, 2009

A simple Rss Feed Parser using LINQ To XML

Download Code

A simple class that can be used to parse rss feed, Check the code attached it will display my twitter updates by parsing the rss feed using the class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
namespace RssFeed

//12-aug-2009 Priyan R
public class RssParser
public RssParser()
Items = new List<RssItem>();
public RssParser(string url):this()
URL = url;
#region Methods
public void Parse()
XDocument doc = XDocument.Load(URL, LoadOptions.None);
Items = (from t in doc.Descendants("item")
select new RssItem()
Title = t.Element("title").Value,
Description = t.Element("description").Value,
Link = t.Element("link").Value


#region properties
public string URL { get; set; }
public List<RssItem> Items { get; set; }
#region RSS Item Class
public class RssItem
public string Title{ get; set; }
public string Description { get; set; }
public string Link { get; set; }

Friday, June 12, 2009

Finding Total Records / Total Count returned By Object Datasource SelectCountMethod

Often SelectCountMethod may be int or long so check the type in object datasource Selected event and store the value in ViewState or a variable so it can be used in the page

protected void odSource_Selected(object sender, ObjectDataSourceStatusEventArgs e)
if (e.ReturnValue.GetType() == typeof(Int32))
ViewState["TotalCount"] = e.ReturnValue;

Sunday, May 10, 2009

I Moved To New VPS Hosting

I moved my websites to a new VPS hosting.For the last 6 months I was managing my own server. here in my place its not trusty ISP problems/Power/Cable , so I am leaving it.
For the last two weeks I was experimenting running windows in virtual machine inside mosso-rackspace cloud using QEMU, Mosso is great but currently they provide only linux , surely they will come with windows,

Now I am using VPS by are not well known, but I trust them. Their plans are cheap and good, 19.99$ 512mb 10gb space 500 GB monthly data transfer. They are using vmware based virtualization.

Saturday, May 9, 2009

Story : Installing WIndows On Mosso RackSpace Cloud With QEMU

Rack space cloud is a very good service with low price. Good customer support, i always got chat session with customer support very soon. They currently provide Linux cloud server only. I am waiting for windows cloud server.

I installed windows 2003 in QEMU , i was not able to Get the KQEMU accelaration layer working. So performance was really poor,

Installation story (Installing 32 bit windows 2003)....

First i created an ubuntu 8.04.2 LTS (hardy) cloud server.

1. Update package list

apt-get update
apt-get upgrade

2. Install QEMU

apt-get install qemu

2. Install X Server

aptitude install xorg

3. Redirect X Display to our system

This was the one main problem i faced. I 'X' forwarded the display to windows pc running XMing. It was really slow.. It took abt 50-100MB data transfer to show the initial windows loading screen.. Took long time to display the screen.. So it is impossible to install windows in this way.

I found a solution X11 VNC

4. Install X11 VNC

apt-get install x11vnc

apt-get install xvfb

Create password file

x11vnc -storepasswd

5. Start X11 VNC create option (will automatically create a display)

x11vnc -usepw -create

6. Connect to X11 VNC From windows using TightVNC

7. Download windows 2003 ISO ( i used windows 2003 trial)

8. Create QEMU hdd image file

qemu-img create win2003.img 20G

9.Install windows

Run qemu with win 2003 iso as cdrom

qemu -m 256 -boot d -cdrom win2003.iso -hda win2003.img -localtime

Problems faced

32 bit windows 2003 installation stuck at installing devices screen , but on restarting once it worked fine.


I was not able setup TAP network working. I used user mode networking with port forwarding option

I run this to forward 3389 port for remote desktop , and 80 for IIS

qemu -hda win2003.img -m 256 -localtime -net nic,model=rtl8139 -net user -redir tcp:3389::3389 -redir tcp:80::80

Installing 64 bit Windows 2003

The qemu version we get with apt-get will not work with win 2003 64
I got stuck "Starting windows" while installing

I installed QEMU 0.90 from source , we need gcc 3.x for doing that,ubuntu comes with gcc 4.x so install gcc 3.4

sudo apt-get install gcc-3.4 g++-3.4

export CC=gcc-3.4

Download qemu 0.9.0 source , then compile & install


tar xzf qemu-0.9.0.tar.gz

cd qemu-0.9.0

make install

I got an error while comiling qemu

Looking for gcc 3.x ./configure: 372: Syntax error: Bad fd number

To fix this edit the ./configure file and change the first line from "#!/bin/sh" to "#!/bin/bash".

Now i was able to install windows 2003 64

qemu-system-x86_64 -m 256 -boot d -cdrom win2003.iso -hda win2003.img -localtime

Installing KQEMU Acceleration Layer

I tried but was not able to get it work

I tried both apt-get kqemu and compiled qemu 0.9.0 and kqemu-1.3 from source,

1st i tried to install with kqemu it got stuck while "starting windows"

Next i tried with -no-kqemu option now 2003 64 installed successfully
After installation i tried with acceleration, initial loading screen came after it screen gone blank.

I installed using


tar xzf kqemu-1.3.0pre11.tar.gz
cd kqemu-1.3

make install

modprobe kqemu

Installation Experience

Windows 2003 32 bit got stuck while "installing devices" , after restarting it worked fine.

Windows 2003 64 bit installed with not problem

It took 4-5 hours to complete the installation !!!!

Really need great patient to do.. Some steps will take long time with not progress moving.. But may not be stuck.. need waiting...

Windows Experience

Its usable but really slow.. I ran some sites on that including my home page, its a little bit slow.. but not so bad.
To install .net framework 3.5 it took 1hr!!

Wednesday, April 8, 2009

Me And Sumesh

I saw sumesh for the second time this monday ( i think after 2 years) . We are often in contact(phone,chat) with each other with programming related for the past 4-5 years.. He is the only programmer i know in Alappuzha, We both started with electronics, programming we both came from a VB6 background , We both are self taught programmers with good experience in Programming/System administration.

Tuesday, March 24, 2009

Malyalam Dictionary Orkut Application

I have created my first orkut application. An english - Malayalam Dictionary. Same as one in my home page.

Wednesday, March 11, 2009


ASP.NET MVC Book written by Scott gu,Scott Hanselman, Rob Conery, and Phil Haack

First chaptter of this book is available as a Free Download. 185 pages of walk-through that takes us into creating a complete MVC application (Called Nerddinner) from scratch. Check the application live at Source code available at codeplex

Download the e-book and source code from scott gu's blog.

Also check scott hanselman's blog about it.

Tuesday, March 3, 2009

SQL Server- Get Rows AS XML, Traverse XML in TSQL

I have a table 'Tags' , see below

To get the rows as XMl

SELECT * FROM Tags for xml auto

The result will be

I want to get the tags separated by coma for the given music id, i wrote a function that
will traverse the XML and return the tags as a single row separated by coma

CREATE FUNCTION [dbo].GetMusicTags
@MusicID INT
SET @i=1
SET @Tag=''
SET @Temp=''
SET @Xdoc=''+(SELECT * FROM Tags WHERE MusicID=@MusicID for xml auto)+''
SET @Count = @Xdoc.query('
{ count(/doc/Tags) }

WHILE @i <= @Count
SELECT @Temp= e.x.value('@Tag[1]', 'VARCHAR(MAX)') FROM
@Xdoc.nodes('/doc/Tags[position()=sql:variable("@i")]') e(x)
SET @Tag=@Tag+@Temp
IF @i<>@Count
SET @Tag=@Tag+','
SET @i = @i + 1

Result will be

Download Sql Script

Wednesday, February 18, 2009

Get start and end date of current week in C#

DayOfWeek day = DateTime.Now.DayOfWeek;
int days = day - DayOfWeek.Monday;
DateTime start = DateTime.Now.AddDays(-days);
DateTime end = start.AddDays(6);
Code from

Monday, February 16, 2009

SQL SERVER: Function To Search Coma or Delimiter separated value in a column

We sometimes stores Coma or other delimiter separated values in a column, to search a particular value in that column, the following function will be helpful.

--30-jan-2009 Priyan R
CREATE FUNCTION [dbo].[IsExistInString]
@Delim VARCHAR(100),
DECLARE @tbl_Split_Data TABLE
SET @pos1=1
INSERT INTO @tbl_Split_Data VALUES(@Data)
WHILE (@pos1<>0)
SET @pos2=CHARINDEX(@Delim,@Data,@pos1)
INSERT INTO @tbl_Split_Data VALUES(SUBSTRING (@Data,@pos1,LEN(@Data)))
INSERT INTO @tbl_Split_Data VALUES(SUBSTRING (@Data,@Pos1,@Pos2-@Pos1))
IF(@pos2<>0) SET @pos2=@pos2+LEN(@Delim)
SET @pos1=@pos2
SELECT @POS1=COUNT(*) FROM @tbl_Split_Data WHERE Data=@ValueToFind

SELECT dbo.IsExistInString('one|$|two|$|three','|$|','one')

C# :Seconds TO String

This functions return a string like 1 hours ago, a day ago etc.

//Returns seconds to 1 hour ago, 10 sec ago etc.
public static string SecondsToString(double seconds)

string time = "";
if (seconds >= 3600)
time =Convert.ToInt32((seconds / 3600)).ToString();
if (seconds > 24)
time = Convert.ToInt32((seconds / 24)).ToString();
time += " days ago";
time += " hrs ago";
else if (seconds >= 60)
time = Convert.ToInt32((seconds / 60)).ToString();
time += " minutes ago";
time = Convert.ToInt32(seconds).ToString();
time += " sec ago";
return time;

Wednesday, February 4, 2009

Programmers And Mathematics

I have been coding in various languages for more than 6 years. Till now i havent used much mathematics for programming. From my experience i feel that one can be a very good programmer without a deep knowledge in maths. But i think proficieny in mathematics will be an added advantage for Programmer. With maths we can write many interesting & funny programs easily without any difficulty.

There is good blog post about it by Steve Yegge.

Friday, January 9, 2009

My Favourite Blog Posts

I often read blog posts mostly of Scott gu,Scott Hanselman,Jeff AtWood ,Phil Haack

This are my favorite blog posts for the last two years


Scott gu's Posts



ASP.NET 2.0 Tips, Tricks, Recipes and Gotchas

Silverlight Tips, Tricks, Tutorials and Links Page

Linq to sql


Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)

The asp:ListView control (Part 1 - Building a Product Listing Page with Clean CSS UI)

First Look at Using Expression Blend with Silverlight 2

First Look at Silverlight 2


ASP.NET MVC Design Gallery

New ASP.NET Charting Control

jQuery Intellisense in VS 2008

Styling a Silverlight Twitter Application with Expression Blend 2

mvc beta released

ASP.NET MVC Preview 5 and Form Posting Scenarios

Silverlight 2 Release Candidate Now Available

jQuery and Microsoft

ASP.NET MVC Preview 4 Release (Part 1)

Silverlight 2 Beta2 Released

ASP.NET MVC Preview 3 Release

Tip/Trick: Creating and Using Silverlight and WPF User Controls

Unit Testing with Silverlight

IIS 7.0 Bit Rate Throttling Module Released

First Look at Using Expression Blend with Silverlight 2

First Look at Silverlight 2

.NET Framework Library Source Code now available

Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)

Using VS 2008 to Create New ASP.NET 2.0 with ASP.NET AJAX 1.0 Projects

ASP.NET 3.5 Extensions CTP Preview Released

ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenario

ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

ASP.NET MVC Framework (Part 2): URL Routing

ASP.NET MVC Framework (Part 1)

Optimizing the Silverlight Install Experience

ASP.NET MVC Framework

Releasing the Source Code for the .NET Framework Libraries

Tip/Trick: Building a ToJSON() Extension Method using .NET 3.5

IIS 7.0 Hits RC0 - Lots of cool new IIS7 Extensions Also Now Available

Linq to sql


The asp:ListView control (Part 1 - Building a Product Listing Page with Clean CSS UI)

Great New ASP.NET 2.0 Data Tutorials Published

Using LINQ to XML (and how to build a custom RSS Feed Reader with it)

VS 2008 JavaScript Debugging

New "Orcas" Language Feature: Query Syntax

New "Orcas" Language Feature: Lambda Expressions

New "Orcas" Language Feature: Extension Methods

New C# "Orcas" Language Features: Automatic Properties, Object Initializers, and Collection Initializers

Tip/Trick: Url Rewriting with ASP.NET

My "First Look at Orcas" Presentation

ASP.NET AJAX 1.0 Source Code Released


Scott Hanselman


Scott Hanselman's 2007 Ultimate Developer and Power Users Tool List for Windows

ASP.NET MVC Design Gallery

.NET 3.5 SP1 GDR is available to download

ASP.NET MVC Samples, Oxite, and Community

Best Code Syntax Highlighter for Snippets in your Blog

The Weekly Source Code 37 - Geolocation/Geotargeting (Reverse IP Address Lookup) in ASP.NET MVC made easy

Web Platform Installer now supports XP - And the Master Plan continues

The Weekly Source Code 36 - PDC, BabySmash and Silverlight Charting

The Weekly Source Code 35 - Zip Compressing ASP.NET Session and Cache State

Survey RESULTS: What .NET Framework features do you use?

Guide to Freeing up Disk Space under Windows Vista

Microsoft Web Application Installer - Open Source Web Apps Delivered and Installed

ASP.NET MVC Beta released - Coolness Ensues

T4 (Text Template Transformation Toolkit) Code Generation - Best Kept Visual Studio Secret

ASP.NET MVC and the new IIS7 Rewrite Module

Web Platform Installer: Trying to make it easier to setup for web development

jQuery to ship with ASP.NET MVC and Visual Studio

The .NET Framework and the Browser's UserAgent String

The Case of the Failing Disk Drive or Windows Home Server Saved My Marriage

On Losing Data and a Family Backup Strategy

Make your Website Mobile and iPhone Friendly - Add Home Screen iPhone Icons and Adjust the ViewPort

Adding OpenSearch to your website and getting in the Browser's Search Box

Developer != Designer

ASP.NET MVC Preview 4 - Using Ajax and Ajax.Form

Hanselminutes Podcast 116 - Distributed Caching with Microsoft's Velocity

Introducing RockScroll

The Weekly Source Code 25 - OpenID Edition

A Smarter (or Pure Evil) ToString with Extension Methods

Memories of Zimbabwe - You can't afford to go home

How do Extension Methods work and why was a new CLR not required?

The Weekly Source Code 22 - C# and VB .NET Libraries to Digg, Flickr, Facebook, YouTube, Twitter, Live Services, Google and other Web 2.0 APIs

Squeezing the most out of IIS7 Media Bit Rate Throttling

The Weekly Source Code 19 - LINQ and More What, Less How

Microsoft - Surviving First Three Weeks as a Remote Employee

Knowing when to ask for help - Microsoft SharedView

Wiring the house for a Home Network

Using an IDE to write PowerShell Scripts

Visual Studio Programmer Themes Gallery

The Weekly Source Code 15 - Tiny Managed Operating System Edition

MS Deploy - New IIS Web Deployment Tool

Verizon FIOS TV - Review and Photo Gallery

.NET Framework Library Source Code available for viewing

How-To: New ASP.NET 3.5 Extensions Video Screencasts

Moq: Linq, Lambdas and Predicates applied to Mock Objects

Wiring the house for a Home Network - Part 6 - Identifying Performance Factors of Home Gigabit Networks

Power Consumption of the HP MediaSmart HP Home Server

Review - HP MediaSmart Windows Home Server

Wiring the house for a Home Network - Part 5 - Gigabit Throughput and Vista

Wiring the house for a Home Network - Part 4 - Thank You Cat 6 Gigabit Ethernet

New Job, New House, New Baby, and Designing a Totally New Home Office

Wiring the new house for a Home Network - Part 3 - ISP Hookup

Screencast HowTo: IIS7 and PHP with FastCGI

Wiring the new house for a Home Network - Part 2 - Design Q&A

Wiring the new house for a Home Network

Improving LINQ Code Smell with Explicit and Implicit Conversion Operators

Scott Hanselman's 2007 Ultimate Developer and Power Users Tool List for Windows

Reading to Be a Better Developer - The Coding4Fun DevKit


XCopy considered harmful - Robocopy or XXCopy or SyncBack

How To Sync your Apple Newton MessagePad with Outlook 2007

Three Things I Learned About Software WHILE NOT in College

The CodingHorror Ultimate Developer Rig Throwdown: Part 1

Leaving Comcast for Verizon Fios - Upgrading the Home Network to Fiber Optic

On Losing Data and a Family Backup Strategy

Making your Application Automatically Update Itself


Jeff AtWood Coding Horror


Dictionary Attacks 101

Best (or Worst) Geek Christmas Ever

Secrets of the JavaScript Ninjas

Reducing Bandwidth

Who Needs Stored Procedures, Anyways?

Recommended Reading for Developers

Why Can't Microsoft Ship Open Source Software?

Large USB Flash Drive Performance

CAPTCHA is Dead, Long Live CAPTCHA!

Jeff Atwood Coding Horror: Programming: Love It or Leave It

The Greatest Invention in Computer Science

Trojans, Rootkits, and the Culture of Fear

Building a PC, Part IV: Now It's Your Turn

Upgrading to a High Efficiency Power Supply

SEOs: the New Pornographers of the Web

Firefox as an IDE

Building a Computer the Google Way

Dude, Where's My 4 Gigabytes of RAM?

Why Can't Programmers.. Program?

Everybody Loves BitTorrent

Remotely Waking Up Your PC

Hard Drive Temperatures: Be Afraid

Is Your Database Under Version Control?


Phil Haack



Everything You Wanted To Know About MVC and MVP But Were Afraid To Ask

Some of great posts i read from Phil Haacks "Not Your Typical Top Ten Of 2008 Post"


" The single most important thing you must do to improve your programming career"

Powerful CSS-Techniques For Effective Coding