Search Code Shode

Wednesday, June 23, 2010

Display Directory Structure Using TreeView Control in ASP.NET

Code Below demonstrate how to Display Directory Structure Using TreeView Control in ASP.NET

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DirectoryListing.aspx.cs" Inherits="DirectoryListing" %>

<head id="Head1" runat="server">
    <title>Directory Listing</title>
    <form id="form1" runat="server">
        <h2>Populating TreeView Nodes On-Demand</h2>

        <asp:TreeView Id="MyTree" 
                      PathSeparator = "|"
                      runat="server" ImageSet="XPDirectoryListing" NodeIndent="15">
            <SelectedNodeStyle BackColor="#B5B5B5"></SelectedNodeStyle>
            <NodeStyle VerticalPadding="2" Font-Names="Tahoma" Font-Size="8pt" HorizontalPadding="2" ForeColor="#000000"></NodeStyle>
            <HoverNodeStyle Font-Underline="True" ForeColor="#6666AA"></HoverNodeStyle>

                <asp:TreeNode Text="Demos" PopulateOnDemand="True" Value="Demos" />


using System;
using System.Data;
using System.IO;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class DirectoryListing : System.Web.UI.Page
    protected void PopulateNode(Object source, TreeNodeEventArgs e)
        TreeNode node = e.Node;

        if (e.Node.Value == "Demos")
            e.Node.Value = Server.MapPath("~/");

        String[] dirs = Directory.GetDirectories(node.Value);

        // Enumerate directories
        foreach (String dir in dirs)
            TreeNode newNode = new TreeNode(Path.GetFileName(dir), dir);

            if (Directory.GetFiles(dir).Length > 0 || Directory.GetDirectories(dir).Length > 0)
                newNode.PopulateOnDemand = true;


        // Enumerate files
        String[] files = Directory.GetFiles(node.Value);

        foreach (String file in files)
            TreeNode newNode = new TreeNode(Path.GetFileName(file), file);

Thursday, June 17, 2010

Format My Source Code for Blogging

Update: July 23rd 2011
Here is a new post on Formatting source code for blogging which uses easier, faster and better approach for Formatting Source Code for Blogging. Check this out:
Format Source Code for Blogging Tool

I've been using Blogger as my blogging engine for a long time. I am very much impressed at how easy it makes it to update your blogs look and feel and how free you are with the HTML and semantic layout of the pages. And now with new Template Designer, life is easier than it was before.

There was one question always in my mind that;

How To Format My Source Code for Blogging??

The thing that seemed to be missing in blogger was allowing developers to copy and paste code into their blogs and allow other users to copy and paste the code from the blog into their own code.

Using SyntaxHighlighter Javascript Library

Adding Syntax Highlighter to Blogger Template

  • Copy the following code and paste it into your Blogger Template just above the </head> tag
<link href='' rel='stylesheet' type='text/css'/> 
<link href='' rel='stylesheet' type='text/css'/> 
<script src='' type='text/javascript'></script> 
<script src='' type='text/javascript'></script> 
<script src='' type='text/javascript'></script> 
<script src='' type='text/javascript'></script> 
<script src='' type='text/javascript'></script> 
<script src='' type='text/javascript'></script> 
<script src='' type='text/javascript'></script> 
<script src='' type='text/javascript'></script> 
<script src='' type='text/javascript'></script> 
<script src='' type='text/javascript'></script> 
<script src='' type='text/javascript'></script> 
<script src='' type='text/javascript'></script> 
<script src='' type='text/javascript'></script> 
<script language='javascript'> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = '';

Wednesday, June 16, 2010

Let Me Google That For You

I just visited a website which really impressed me.
It really simplify to direct someone to search what on Google??

If you want some one to search "Code Shode" on google and does not want to bother that person to:
  • Open a new window
  • Type
  • Type "Code Shode " in text box 
  • Press Google Search

Simply send them this link.

Just like that!

Tuesday, June 15, 2010

How to Pass Query String to User Control : ASP.NET

I have been often asked by people that how to pass query string to user control in ASP.NET.
I decided to solve this problem in this blog post.

In this post I am using example of a Menu Control (used as User Control) which needs to be binded dynamically depending on query string provided to the main page containing user control.

This can be done easily by using public property in the user control.

Following 3 easy steps will help in accomplishing this task!

Step 1:

In your user controls create this property (you can change this according to your situation)


    private string menuId = string.Empty;

    #region Property
    public string MenuID
            menuId = value;



    Private menuId As String = String.Empty

#Region "Property"
    Public WriteOnly Property ChangeMenuID() As String
        Set(value As String)
            menuId = value
        End Set
    End Property

#End Region

Step 2:
Set Menu ID property of your user control from parent page like:


YourUserControlID.MenuID = Request.QueryString["menuid"].ToString();// or from any other variable


YourUserControlID.MenuID = Request.QueryString("menuid").ToString() ' or from any other variable

Step 3:
Write this function in your user control which will bing the Menu from database depending on query string provided to the parent page having user control.


    // This function is to be written in the user control
    public void BindMenuData()
        SqlCommand sqlCmd = new SqlCommand();
        sqlCmd.CommandText = "select * from [YourTableName] Where MenuID = @MenuID";
        sqlCmd.Parameters.AddWithValue("@MenuID", menuId);
        sqlCmd.CommandType = CommandType.Text;

        SqlConnection sqlCOn = new SqlConnection("Connection String.. bla bla");
        SqlDataAdapter adapter = new SqlDataAdapter(sqlCmd);
        DataSet ds = new DataSet();
        Menu1.DataSource = ds;


    'This function is to be written in the user control
    Public Sub BindMenuData()
        Dim sqlCmd As New SqlCommand()
        sqlCmd.CommandText = "select * from [YourTableName] Where MenuID = @MenuID"
        sqlCmd.Parameters.AddWithValue("@MenuID", menuId)
        sqlCmd.CommandType = CommandType.Text

        Dim sqlCOn As New SqlConnection("Connection String.. bla bla")
        Dim adapter As New SqlDataAdapter(sqlCmd)
        Dim ds As New DataSet()
        Menu1.DataSource = ds
    End Sub

That's That! ;)

Still have confusion ??
Feel free to ask!

Ways to Pass Data Between Web Forms

In this blog post, i will be showing different ways to pass data between webforms.
Different techniques could be implemented, it all depends on what serves you most!
We all know that Http is stateless, so data should be stored somewhere in order
to be able to retrieve it.

1. Query String

2. Cookies

3. Session variables

4. Cross Page Posting

5. Submit form

6. Server.Transfer or Server.Execute

We will talk in details about each one and which kind of data it could store.

Using Query string variables, you can pass data between
webforms. below is an example

Ex: Suppose you want to pass the TextBox1.Text variable from WebForm1 to WebForm2
on button click event.

protected void Button1_Click(object sender, EventArgs e)
Response.Redirect("WebForm2.aspx?id=" + TextBox1.Text);

To Read the value of "id" in WebForm2, you should use the below code

string queryStringID = Request.QueryString["id"];

Now queryStringID will hold the data from the querystring.

Really Simple JavaScript toTitleCase() Implementation

This function is not very much efficient, but it does what I needed it to, and will
probably be sufficient for your needs almost all the time. The script extends the
JavaScript String type with a new toTitleCase() method,
which simply converts all the words in the string to their title-cased (i.e. the
first letter is capitalized) equivalent. It effectively ignores words that
are already upper-cased, and works fine with strings that include numbers.

String.prototype.toTitleCase = function ()  { var A = this.split(' '), B = []; for (var i = 0; A[i] !== undefined; i++)  B[B.length] = A[i].substr(0, 1).toUpperCase() + A[i].substr(1);  return B.join(' '); }

Include the above snippet in your script somewhere, and you can then call the method
in the same way as the other String functions:
var s = "This is a sentence.";
var t = s.toTitleCase();

Neat and simple, and sufficient for most of your JavaScript title-casing needs.

Saturday, June 12, 2010

Inline ASP.NET Tags

There are all sorts of different inline tags, and i haven't found a place that explains

They are all in ONE place, so here is the quick view...

<% ... %>

The most basic inline tag, basically runs normal code:
<% if (User.IsInRole("admin")) { %>
You can see this
<% } else { %>
You are no admin fool!
<%} %>

<%= ... %>

Used for small chunks of information, usually from objects and single pieces of
information like a single string or int variable:
The Date is now <%= DateTime.Now.ToShortDateString() %>
The value of string1 is <%= string1 %>
*note: <%= is the equivalent of Response.Write() - Courtesy of Adam from the

Convert Month Integer Into A Month Name in ASP.NET

Turn 11 into 'November', 3 into 'March', etc.

Simple line of code that makes life easy, it's even culture sensitive:


Tuesday, June 8, 2010

Visual Studio .NET 2005 Keyboard Shortcuts

Class Diagram

Num +






Num -

DataSet Editor



Microsoft Visual Studio Professional 2005 [OLD VERSION]Professional Visual Studio 2005Visual Studio 2005 All-In-One Desk Reference For Dummies (For Dummies (Computer/Tech))Practical Code Generation in .NET: Covering Visual Studio 2005, 2008, and 2010 (Addison-Wesley Microsoft Technology Series)

Auto Refresh Web Page

The Meta tag Refresh has been around for a long time. Often you see it when an old web page has moved to a new web page. You usually put the meta tag in the header of your page. The syntax is:
<meta http-equiv="Refresh" content="n;url">
Where n is the number of seconds
And url is the url to refresh to.
If you leave the url off then the page refreshes itself.

In this sample code, the page updates the current time every 3 seconds. In the pageload event I have this code to set the meta tag:
if (Page.Header != null)
 HtmlHead hh = this.Page.Header;
 HtmlMeta hm = new HtmlMeta();
 hm.Attributes.Add("http-equiv", "Refresh");
 hm.Attributes.Add("content", "3");

You can place this code in any other event which depends on your requirement like
if you need to refresh page after an event is fired.

When using Master Page, given code can be altered as:

if (this.Master.Page.Header != null)
 HtmlHead hh = this.Master.Page.Header;
 HtmlMeta hm = new HtmlMeta();
 hm.Attributes.Add("http-equiv", "Refresh");
 hm.Attributes.Add("content", "3");
Hope it hepls!

Meta Tags Optimising Your Website for Internet Search EnginesVariations in use of meta tag descriptions by Web pages in different languages [An article from: Information Processing and Management]A co-training framework for searching XML documents [An article from: Information Systems]HTML5: Up and Running

Tuesday, June 1, 2010

C# Regular Expression (Regex) Examples in .NET

More Advanced Regular Expression Syntax

This article continues from Learn Regular Expression (Regex) syntax with C# and
and covers character escapes,
match grouping, some C# code examples, matching boundaries and RegexOptions.

Matching special characters with character escapes

Special characters such as Tab and carriage return are matched using character escapes.
The syntax is similar to C and C#. The common character escapes are listed below.
Special Character
Matches a tab
Matches a carriage return
Matches a new line
Matches a Unicode character
using hexadecimal representation.
Exactly four digits must be specified.

In this example, the Regular Expression pattern matches one or more word characters
followed by a carriage return then a new line.
Text:    an anaconda ate
Anna Jones
Regex:   \w+\r\n
Depending on your operating system you might have to combine the
\r and
\n character escapes to create the correct
new line sequence for your platform. For Microsoft Windows systems you should generally
use \r\n which
is a carriage return then line feed (CRLF). To simply match the end of a line or
string use the dollar sign ($).

Kingston 4 GB Class 4 SDHC Flash Memory Card SD4/4GBETBlackBerry Bold 9700 Phone (AT&T)Breach of TrustAvatar (Two-Disc Blu-ray/DVD Combo) [Blu-ray]

Learn Regular Expression (Regex) syntax with C# and .NET

What are Regular Expressions?
Regular Expressions are a powerful pattern matching language that is part of many
modern programming languages. Regular Expressions allow you to apply a
pattern to an input string and return a list
of the matches within the text. Regular expressions also allow text to be replaced
using replacement patterns. It is a very powerful version of find and replace.
There are two parts to learning Regular Expressions;
  • learning
    the Regex syntax
  • learning
    how to work with Regex in your programming language
This article introduces you to the Regular Expression syntax. After learning the
syntax for Regular Expressions you can use it many different languages as the syntax
is fairly similar between languages.
Microsoft's .NET Framework contains a set of classes for working with Regular Expressions
in theSystem.Text.RegularExpressions namespace.

Download the Regular Expression Designer

When learning Regular Expressions, it helps to have a tool that you can use to test
Regex patterns. Rad Software has a Free Regular Expression Tool
available for download that will help as you go through the article.

The basics - Finding text

Regular Expressions are similar to find and replace in that ordinary characters
match themselves. If I want to match the word "went" the Regular Expression pattern
would be "went".
Text:    Anna Jones and a friend went to lunch
Regex:   went
Matches: Anna Jones and a friend went to lunch
The following are special characters when working with Regular Expressions. They
will be discussed throughout the article.
. $ ^ { [ ( | ) * + ? \
Java Regular Expressions: Taming the java.util.regex EngineRegular Expressions CookbookMastering Regular ExpressionsSams Teach Yourself Regular Expressions in 10 Minutes