Search Code Shode

Wednesday, December 8, 2010

Active Directory Authentication for ASP.NET Website Users

ASP.NET membership provides the ability to authenticate users to your web application using forms based authentication against a database of users or directory services.  This article explains the steps required to provide authentication against Active Directory, either for new sites with no authentication, or for existing sites using database authentication.

Step 1 – Set up the Active Directory connection string
The Active Directory connection string is simliar to the database connection string used in ASP.NET, except that it references an LDAP address.  The connection string is specified in the web.config file.
The following string will authenticate users in the entire tree:

    <add name="ADConnectionString" 

If you want to restrict authentication to a particular OU, then you specify it in the connection string like so:

    <add name="ADConnectionString" 

Wednesday, July 21, 2010

Validating/Masking Numbers In TextBox using Regular Expression Validator and Javascript

It wont allow spaces before or after the digits but it wont if there are only spaces so you need RequiredFieldValidator too
the RegularExpressionValidator to validate the only number without using JavaScript. So something like this:

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox1"
    ValidationExpression="\d+" Display="Static" EnableClientScript="true" ErrorMessage="Please enter numbers only"

Where as if you want to forbid user to type, copy/paste, drag/drop any text other than numbers, or if you want extract numbers from user entered values, you can use code below:

For this example i am trying to validate user to enter age in a textbox, which should not be other than number:

<asp:TextBox ID="txtAge" MaxLength="3" onblur="extractNumber(this,2,false);"
    onkeypress="return blockNonNumbers(this, event, true, false);"
    onkeyup="extractNumber(this,2,false);" runat="server">
<asp:RequiredFieldValidator ControlToValidate="txtAge" ErrorMessage="Please Enter Age"
    ID="rfvtxtAge" runat="server">*
<asp:RegularExpressionValidator ControlToValidate="txtAge"
    ErrorMessage="Please Enter Valid Age" ID="revtxtAge" runat="server"
    SetFocusOnError="true" ValidationExpression="^\d+$">*

Using asp:RequiredFieldValidator makes it sure that user enter some value.
Script below extract numbers / forbid user to enter non-numeric values:

<script type="text/javascript">
    function extractNumber(obj, decimalPlaces, allowNegative) {
        var temp = obj.value;

        // avoid changing things if already formatted correctly
        var reg0Str = '[0-9]*';
        if (decimalPlaces > 0) {
            reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
        } else if (decimalPlaces < 0) {
            reg0Str += '\\.?[0-9]*';
        reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
        reg0Str = reg0Str + '$';
        var reg0 = new RegExp(reg0Str);
        if (reg0.test(temp)) return true;

        // first replace all non numbers
        var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
        var reg1 = new RegExp(reg1Str, 'g');
        temp = temp.replace(reg1, '');

        if (allowNegative) {
            // replace extra negative
            var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
            var reg2 = /-/g;
            temp = temp.replace(reg2, '');
            if (hasNegative) temp = '-' + temp;

        if (decimalPlaces != 0) {
            var reg3 = /\./g;
            var reg3Array = reg3.exec(temp);
            if (reg3Array != null) {
                // keep only first occurrence of .
                //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
                var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
                reg3Right = reg3Right.replace(reg3, '');
                reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
                temp = temp.substring(0, reg3Array.index) + '.' + reg3Right;

        obj.value = temp;
    function blockNonNumbers(obj, e, allowDecimal, allowNegative) {
        var key;
        var isCtrl = false;
        var keychar;
        var reg;

        if (window.event) {
            key = e.keyCode;
            isCtrl = window.event.ctrlKey
        else if (e.which) {
            key = e.which;
            isCtrl = e.ctrlKey;

        if (isNaN(key)) return true;

        keychar = String.fromCharCode(key);

        // check for backspace or delete, or if Ctrl was pressed
        if (key == 8 || isCtrl) {
            return true;

        reg = /\d/;
        var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
        var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;

        return isFirstN || isFirstD || reg.test(keychar);

Hope it helps!

Happy Coding!
Happy Shoding!

Sunday, July 11, 2010

How Secure Is My Password?


Type your Password

Friday, July 2, 2010

Event Delegation ASP.NET: Raise Event from User Control to Parent Page

"What is delegate?" we all have faced this question in one or more interview and the most common answer is "Function pointer". I have always been confused that what the hell are delegates? What to do with them in Web Development?? Now i came to realize the importance of delegates.

Here I am showing a simple example of delegate.
I have one user control and one aspx page. The user control contains one button. When user click on this button, I will call a method on main page using delegate.

Here is my user control:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl.ascx.cs"
    Inherits="Delegate_WebUserControl" %>
<asp:Button ID="btnTest" runat="server" Text="I am Inside User Control" OnClick="btnTest_Click" />


<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="WebUserControl1.ascx.vb" Inherits="Delegate_WebUserControl" %>
<asp:Button ID="btnTest" runat="server" Text="I am Inside User Control" OnClick="btnTest_Click" />

On WebUserControl.ascx.cs I have written simple delegate and event handler as shown below:

Code Behind


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

public partial class Delegate_WebUserControl : System.Web.UI.UserControl
    // Delegate declaration 
    public delegate void OnButtonClick(string strValue);
    // Event declaration 
    public event OnButtonClick btnHandler;
    // Page load 
    protected void Page_Load(object sender, EventArgs e)
    protected void btnTest_Click(object sender, EventArgs e)
        // Check if event is null 
        if (btnHandler != null)
        // Write some text to output 
        Response.Write("User Control’s Button Click <BR/>");

Thursday, July 1, 2010

Automatically Refresh User Session Using jQuery ASP.NET - Behind the Scenes

Incredibly simple script will keep your user's session alive without any worries

Now this is something that may or may not be useful to a lot of people, depending on your situation, you may want the user to elect to refresh their Session or not (like banks usually do); but this is for applications that may have a lot of idle time and users are annoyed with their Sessions dying... considering most users don't know what a Session is, but they know that the application stops working correctly.

It uses jQuery and is incredibly simple, just a few lines of code, and no screen flicker or any annoyance to the user at all; ignorance is bliss.

First I include the following in the code-behind in any page you need to keep refreshed (works on masterpages as well):



protected int timeout;
protected void Page_Load(object sender, EventArgs e)
    // one minute prior to timeout (milliseconds)
    timeout = (Session.Timeout * 60000) - 60000;


Protected timeout As Integer
Protected Sub Page_Load(sender As Object, e As EventArgs)
    ' one minute prior to timeout (milliseconds)
    timeout = (Session.Timeout * 60000) - 60000
End Sub

Then add this jQuery to your script:

aspx or master page:
var to;
    to = setTimeout("TimedOut()",);

function TimedOut()
    $.post( "refresh_session.aspx", null,
        if(data == "success")
            to = setTimeout("TimedOut()", );

Create Edit Word Document using C# VB.NET

Here I am going to demonstrate How to Create and Edit MS Word Document  using C# and VB.NET

To create or edit MS Word document, first of all we need to add two references to our project.
  • Microsoft.Office.Core
  • Microsoft.Office.Interop.Word

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