戰地連結︰ Home My Flickr NBA.com About

2009年10月9日星期五

PHP crash with some MySql functions

Overview

I has been playing with a WAMP web site using Joomla 1.5 as the CMS. Actually I am just doing the setup when I encounter this issue. When I reached the “Database Configuration” step in Joomla installation, Apache keeps crashing when I proceeded, and the Event Log said that:

Faulting application httpd.exe, version 2.2.11.0, faulting module > php5ts.dll, version 5.2.10.10, fault address 0x0000ac6a.

Again, with some Googling I found that I am not alone and there are several solutions for this issue, which is caused by wrong "libMySql.dll" module used.

Both MySQL and PHP provides the "libMySql.dll" module. When using PHP, we should use the "libMySql.dll" module provided by PHP, but not MySQL.

Reference

PHP Installation, MySQL

php使用MySql函数导致Apache(iis)崩溃的问题

PHP Crash when use some mysql function

Steps

There are several ways to solve this problem, I use the first method:

  • Rename the "libMySql.dll" file located at your MySQL “<InstallDir>/bin” folder
  • Remove your MySQL “<InstallDir>/bin” folder path from the system’s path environment variable
  • Copy the "libMySql.dll" file from your PHP install folder to “%SystemRoot%/system32” folder

2009年10月7日星期三

Unlock files used by processes

Overview

I think most of the Windows users have seen the screen saying that “Cannot delete XXX: It is being used by another person or program”. This is quite annoying as you don’t have a clue what is actually locking the file. Now I would like to share some of the programs I used (or heard) to solve this problem.

Reference

Unlocker - http://ccollomb.free.fr/unlocker/

It is a very nice program which add a extensions to your Windows Explorer, so that you can right-click on any file/folder and select the “unlocker” option. It will shows all processes locking the file for your to decide what to do next. However the latest version (1.8.7) does not supports 64-bit OS.

LockHunter - http://lockhunter.com/

LockHunter is a similar tool to Unlocker, Windows Explorer extensions. However it works for both 32-bit and 64-bit OS, and it delete files to recycle bin.

Process Explorer - http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

Finding what files (handles) is used by a process is just one of the features of Process Explorer. As it actually shows much more information than the list of handles used. Because it is more powerful, it is also more complicated to use.

To use Process Explorer for unlocking files from processes, following the steps below:

  1. Select "Find" –> "Find Handle or DLL"
  2. Enter the full path of the file as the Handle substring, click "Search"
  3. For each of the search results that match the file you want to delete, right-click on the handle and choose "Close Handle"
  4. Done! However I recommend using “LockHunter” if you ONLY want to unlock files. ;-)

2009年9月16日星期三

Single Sign-on for ASP.NET 3.5 and Legacy ASP

Overview

I got a task on setting Single Sign-on (SSO) for a ASP.NET site and legacy ASP site. For this, Ting Huang has written a very nice post on wwwcoder.com. The idea behind is to create a “bare bone” API for the FormsAuthentication class (without the need of HttpContext), and wrap it in a COM object, which can be used by ASP page. However the post is regarding ASP.NET 1.1 and I am using ASP.NET 3.5, for which the FormsAuthentication class is quite different.

With some more googling I found the way to manually create the authentication ticket, encrypt it and save it to cookie. Using these technique I can make a ASP page create a authenticate cookie which can be consumed and recognized by a ASP.NET web application.

Reference

  1. Creating a Single Sign-on for ASP.NET Application and Legacy ASP Application (Part II)
  2. Single Sign-On for everyone
  3. AppDomainSetup.ConfigurationFile Property

Steps

Write the “bare bone” API for the FormsAuthentication class

using System;

using System.Web.Security;

 

namespace SingleSignon

{

    public class AuthAPI

    {

        public AuthAPI()

        { }

 

        public string FormsCookieName

        {

            get { return FormsAuthentication.FormsCookieName; }

        }

 

        public void Initialize()

        {

            FormsAuthentication.Initialize();

        }

 

        public string SetAuthCookie(

              string userName,

              bool createPersistentCookie)

        {

            try

            {

                FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);

                return "success";

            }

            catch (Exception e)

            {

                return "error: " + e.Message;

            }

        }

 

        public string GetAuthCookieValue(

              string userName,

              bool createPersistentCookie

            )

        {

            try

            {

                FormsAuthenticationTicket newticket = new FormsAuthenticationTicket(userName, createPersistentCookie, 30);

                return FormsAuthentication.Encrypt(newticket);

            }

            catch (Exception e)

            {

                return "error: " + e.StackTrace;

            }

        }

 

        public void GetAuthTicketInfo(

            string cookieValue,

            out string cookiePath,

            out string expireDate,

            out bool expired,

            out bool isPersistent,

            out string issueDate,

            out string userName,

            out string userData,

            out int version

            )

        {

            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookieValue);

            cookiePath = ticket.CookiePath;

            expireDate = ticket.Expiration.ToShortDateString();

            expired = ticket.Expired;

            isPersistent = ticket.IsPersistent;

            issueDate = ticket.IssueDate.ToShortDateString();

            userName = ticket.Name;

            userData = ticket.UserData;

            version = ticket.Version;

        }

    }

}

Setup web.config file for Forms Authentication

<authentication mode="Forms">

  <forms name="DEMO" loginUrl="login.aspx" protection="All" timeout="30" path="/" />

</authentication>

<authorization>

  <deny users="?" />

</authorization>

<machineKey validationKey='9804…CB69' decryptionKey='FEA…D648' validation='SHA1'/>

Be reminded to set the "machineKey" for the ASP.NET web application and share it with legacy ASP site.

Add “AuthAPI” assembly to Global Assembly Cache (GAC) and register it as a COM object

The legacy ASP site is going to use the AuthAPI through COM interface, so we should first register the API as a COM object. To do this, we have to:

  1. Sign the assembly
  2. Add the assembly to GAC. I use the “gacutil.exe” tool at
    C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe
  3. Register the assembly as a COM object. Use “regasm” tool at
    C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\regasm

Indeed you can use the "Post-build event command line" in Visual Studio to do these actions every time you rebuild the assembly. Just remember to unregister the COM object and uninstall the assembly from GAC first.

Setup/Create the “dllhost.exe.config” file for the legacy ASP site

You may wonder how the “AuthAPI” load the Forms authentication settings, does it read from the web.config file of the ASP.NET web app? No, actually it does not have any linkage to the web app. So how can we know which config file is the AuthAPI looking for? We can get the file path from “AppDomain.CurrentDomain.SetupInformation.ConfigurationFile”, and it turns out to be a config file at “C:\WINDOWS\system32\dllhost.exe.config”. It make sense as “dllhost.exe” is the “DCOM DLL Host Process”.

OK so we have to edit this “dllhost.exe.config” file to configure the FormsAuthentication component of “AuthAPI”. You may not see this file in “C:\WINDOWS\system32\”, so just create it and put the Forms authentication configuration in it.

Sample of “dllhost.exe.config” file

<configuration>

  <configSections>

    <sectionGroup name="system.web.extensions" type="System.Web...">

      <!-- Copy all settings from web.config file -->

    </sectionGroup>

  </configSections>

  <system.web>

    <!-- Copy Forms Authentication settings and Machine key from web.config file -->

  </system.web>

</configuration>

Use “AuthAPI” in legacy ASP site to create a Cookie with valid authentication ticket

Now we have the COM object setup and configured, we can use it in our legacy ASP site. The following code shows the function of creating a authentication ticket and putting it into a Cookie. If the ASP.NET web app and the legacy ASP site share the same domain. The Cookie will be shared between them and the Single Sign-on is achieved!

<body>
 
    <%          
            Set ulogin = Server.CreateObject("SingleSignon.AuthAPI")
            userName = "TestUser"
            Call ulogin.Initialize()
            response.write("FormsCookieName: " + ulogin.FormsCookieName() + "<br>")
            
            authCookieValue = ulogin.GetAuthCookieValue(userName, true)
            response.write("AuthCookieValue: " + authCookieValue)
            
            Call AddCookie ( ulogin.FormsCookieName(), "", authCookieValue, 30, "")
            set ulogin = nothing
    %>
 
</body>

2009年9月9日星期三

Disabling Time Synchronization under Virtual PC 2007

Overview

VPC with Virtual Machine Additions installed will automatically synchronize its time with host. Virtual PC Guy tells us how to disable it in his post.

Reference

Disabling Time Synchronization under Virtual PC 2007

Steps

  1. Shut down the VPC (I found that cannot use “Save state”)
  2. Open the .VMC file with notepad and add the "components" element in it:

    <integration>

      <microsoft>

        <mouse>

          <allow type="boolean">true</allow>

        </mouse>

        <!--Add the "components" element-->

        <components>

          <host_time_sync>

            <enabled type="boolean">false</enabled>

          </host_time_sync>

        </components>

  3. Save the .VMC file and restart VPC, done!

Associate XSD to XML file to enable IntelliSense

Overview

We .Net developers use IntelliSense extensively in our everyone work. I am happy using IntelliSense for XML files like web.config file. Then one day I come across a XML file with schema not available out-of-the-box from VS (think about NHibernate hbm files). How can I use IntelliSense with it?

Reference

XML Schemas dialog in Visual Studio 2008

Steps

To use schema(s) for a XML file

  1. Open a XML file in Visual Studio 2008
  2. In menu bar, select "XML" => "Schemas…"
  3. In the "XML Schemas" windows, select "Use this Schema" in the "Use" column next to your desired schema
  4. Click OK, done!

The "XML Schemas" windows will search for schema files (.XSD) in your project or in folder %VS 2008 install folder%\xml\Schemas. You can also manually add schemas files using the "Add…" button

Introduction to ASP.NET Forms Authentication

In ASP.NET, forms authentication means that users authenticate themselves using a Web form. This feature is provided by the HTTP module FormsAuthenticationModule. Setting up forms authentication in ASP.NET is quite simple and is presented in a post at WindowsDevCenter.com.

Reference

  1. ASP.NET Forms Authentication - Part 1
  2. Explained: Forms Authentication in ASP.NET 2.0 (MSDN)
  3. FormsAuthentication Class (MSDN)

Steps

Enable anonymous access in IIS.

Anonymous access is enabled by default. If not, enable it manually for the web application.

Modify web.config file to allow Forms Authentication

To allow Forms Authentication, first we have to add the "authentication" element under "system.web" in web.config.

  1. In the "authentication" element, set the "mode" attribute to “Forms” to specify Forms Authentication.
  2. Add a "forms" element under "authentication" element to specify configuration settings for Forms Authentication
  3. Add a "authorization" element under "authentication" element to deny all anonymous users and redirect them to login page.

Code Snippet (web.config):

<configuration>

  <system.web>

    <authentication mode="Forms">

      <forms name="DEMO"

            loginUrl="login.aspx"

            protection="All"

            timeout="30"

            path="/" />

    </authentication>

    <authorization>

      <deny users="?" />

    </authorization>

  </system.web>

</configuration>

Create the login page

The login page is where denied users will be redirected to. It is referenced by "loginUrl" attribute in "forms" element. As shown by the above code snippet, our login page will be “login.aspx”.

Code Snippet (login.aspx.cs)

protected void Login_Click(Object sender, EventArgs E)

{

    if ((UserName.Value == "username") &&

        (UserPass.Value == "password"))

    {

        FormsAuthentication.RedirectFromLoginPage(UserName.Value, PersistCookie.Checked);

    }

    else

    {

        lblResults.Text = "Invalid Credentials: Please try again";

    }

}

The above code snippet is the onClick event of the login button. When it is fired, it will:

  1. Validate the user credentials entered. In this case the validation logic is completely provided by us and only allow one user to login.
  2. If the user is valid, FormsAuthentication.RedirectFromLoginPage() is called to authenticate the user and redirect back to the page he/she wants to visit.
  3. Else a warning message is shown.

Configure user credentials in web.config

Usually we will store the user credentials in a Database. However for easy implementation (or for testing purpose) we can also set user credentials in web.config file.

By adding "credentials" element under "forms" element, we can add user credentials in username/password pair format.

<forms>

    <credentials passwordFormat="Clear">

      <user name="user1" password="password1"/>

      <user name="user2" password="password2"/>

      <user name="user3" password="password3"/>

    </credentials>

</forms>

Then we can use FormsAuthentication.Authenticate() method to validate user credentials against those stored in web.config.

2009年9月3日星期四

ASP.NET MVC - Get Started

Overview

I just started learning ASP.NET MVC, and would like to list some learning materials links here.

Reference

Official ASP.NET MVC Tutorials - http://www.asp.net/learn/mvc/

Download "Microsoft Web Platform Installer" to get ASP.NET MVC - http://www.microsoft.com/web/downloads/platform.aspx

NerdDinner at CodePlex - http://nerddinner.codeplex.com/

NerdDinner Site - http://www.nerddinner.com/

2009年7月22日星期三

Installing Driver for Legacy Network Adapter on Win2k3 x64 VPC (Hyper-V)

Overview

I installed a 64-bit Windows 2003 R2 Enterprise SP2 on one of my Hyper-V VPC, and add a Legacy Network Adaptor to it. However the network adapter is not automatically installed in the x64 win 2k3 because its driver is not available.

With some Googling I found that 64-bit version of win 2k3 and xp are not supported with corresponding Legacy Network Adaptor driver. Someone suggested a workaround by using the equivalent Vista driver (both x86 and x64).

So I go the driver files from a machine running on x86 Vista and tried it. But the driver installation terminated with Error: "Driver not intended for this platform".

Suspecting this maybe due to the x86/x64 difference, I got another set of driver files from a x64 Windows Server 2008. This time the driver installation ran smoothly and the Network Adaptor works well!

Directory containing Legacy Network Adaptor driver:

Vista:
%windir%\system32\driverstore\FileRepository\dc21x4vm.inf_7d8c6569

Windows Server 2008:
%windir%\system32\driverstore\FileRepository\dc21x4vm.inf_e14caac7

Reference

Windows XP x64 in Hyper-V - Network Drivers

2009年7月20日星期一

ASP.NET User Control - Part 1

Overview

User Control is quite useful in creating a customized control which can be reused throughout pages. Instead of creating a custom server control, developers can create user control which (in my opinion) is easier to create and modify the control layout.

In this part, I will talk about how to create a user control and include it in an .aspx page.

Reference

ASP.NET User Controls Overview

How to: Include a User Control in an ASP.NET Web Page

Steps

Create a User Control

Creating a user control is very simple with few steps:

  1. You need to have a Web Application Project
  2. In Solution Explorer, right-click on the project's name (or a folder), select "Add" => "New Item..."
  3. Select "Web User Control" under "Web" category, give the control a name and click "Add"
  4. Done!

The newly created user control consists of a .ascx (not .aspx) page and a code behind file (just ignore the designer file). The .ascx page currently contains nothing but a "@ Control" directive.

User control .ascx page is very much like a snippet of an .aspx page, you can modify the layout of the user control by adding HTML tags or ASP.NET controls in it just like what you do to .aspx page. Below is the code of a very simple .ascx page:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestUserControl.ascx.cs" Inherits="MyTestWeb.Web.Controls.TestUserControl" %>

 

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />

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

<asp:Button ID="BtnSubmit" runat="server" Text="Submit" />

 

Include a User Control in an .aspx page

After a User Control is created, it can be used by any .aspx page within the same Web Application by including the control into the page.

To Include a User Control, we have to do 2 things:

  1. Create a "@ Register" directive which specify the "TagPrefix", "TagName" and "Src" (Source file) of the User Control.
  2. Declare the User Control with tag "<TagPrefix:TagName   />" just like any other ASP.NET control (the difference is ASP.NET Control start with TagPrefix "asp")

Below shows the code of a simple .aspx page including the User Control we just created.

<%@ Page Language="C#" MasterPageFile="~/Pages/Global.Master" AutoEventWireup="true"

    CodeBehind="TestPageWithMaster.aspx.cs" Inherits="MyTestWeb.Web.Pages.TestPageWithMaster"

    Title="Untitled Page" %>

 

<%-- "@ Register" directive --%>

<%@ Register TagPrefix="uc" TagName="TestUserControl" Src="~/Controls/TestUserControl.ascx" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    <form runat="server">

 

        <%-- User Control declaration --%>

        <uc:TestUserControl ID="TestUserControl1" runat="server" />

 

    </form>

</asp:Content>

2009年7月8日星期三

Client side validation skipped if submit Button have "onClientClick" JavaScript function

Overview

I have a form using ASP.NET validation controls, I have been using these ASP.NET validators for quite a time and they behaved well. However the problem come when I added a "onClientClick" event handler to the form submit button, and then the validation is just skipped and the form post back every time.

The problem is that the "onClientClick" event get fired before the validation so the validation is skipped. To solve this, we can use the JavaScript function "Page_ClientValidate()" to trigger the client side validation.

Reference

asp:Button Validation with OnClientClick javascript - Not Validating

ASP.NET Validation in Depth

Code Snippet

You can tell "Page_ClientValidate()" to only validate controls of a particular validation group by passing the validation group name as parameter.

function BtnSubmitButton_click()

        {

            if (Page_ClientValidate("ValidationGroup"))

            {

                return confirm("Submit this form?");

            }

            return false;

        }

2009年5月29日星期五

Moved files cannot inherit destination folder's permission, but copied files can.

Overview

When I want to share a file with others in the same network, I move the file to my shared folder. However, sometimes I receive complains from my colleagues saying that they don't have permission to read the shared files.

At the end, I found that a copied file can inherit the permission of the destination folder, but a moved file cannot. I think that it is because the copy action create a new file while the move action (within same volume) only change the hosting folder of the original file.

With some googling, I found that this behaviors is documented by Microsoft. The article also provide a way to change this behavior by modifying registry.

Reference

How permissions are handled when you copy and move files and folders

Step

Let moved files inherit destination folder's permission like copied files

  1. Run "regedit" (Fire up Registry Editor)
  2. Go to "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer"
  3. Add a "DWORD" value with name "MoveSecurityAttributes" and Value "0"

2009年5月19日星期二

Using mdev of busybox

Overview

mdev is a device manager like udev, actually it is a "mini udev". mdev is very useful in embedded system as it is included in newer version of busybox. mdev can also shorten boot up time significantly compared to udev. This can be vital to some embedded system.

Below shows a sample startup script for mdev.

Reference

mdev – mini udev in busybox

mdev的使用方法和原理。

Code Snippet

Here is the startup script I used:

#!/bin/sh

echo "Mounting sysfs"
mount -t sysfs sysfs /sys

echo "Mounting /dev"
mount -t tmpfs mdev /dev

echo "Creating /dev/pts"
mkdir /dev/pts

echo "Mounting pts"
mount -t devpts devpts /dev/pts

echo "Echoing hotplug"
echo /sbin/mdev > /proc/sys/kernel/hotplug

echo "mdev -s"
mdev -s

2009年5月17日星期日

Create Private Network for VPCs with Microsoft Loopback Adaptor

Overview

If you want to add your VPCs into a network so that they (and your host machine) can access other via TCP/IP, what will you do? You can assign your physical network adaptor to VPCs so that they will be on the same network as your host machine, but first you need a DHCP server, and all your VPCs will be exposed to external.

Indeed you can use "Microsoft Loopback Adaptor" to add a virtual network adaptor to your host computer. Then you can assign the Loopback Adaptor to your VPCs to form a Private Virtual Network, so that each VPC can communicate with each other and host machine, but not accessible by external computers.

Reference

Install Microsoft Loopback Adapter

Using Microsoft Loopback Adapter

Virtual PC IP Routing: enabling VPC NAT & loopback connector at the same time

Step

To Install Microsoft Loopback Adaptor

Adding Microsoft Loopback Adaptor is like adding a new hardware in Windows. This part is copied from Reference 1.

  1. In the host operating system, right-click My Computer, and then select Properties. Depending on the style of the start menu, My Computer may be located in the Start menu.
  2. In the System Properties dialog box, on the Hardware tab, click Add Hardware Wizard.
  3. In the Add Hardware dialog box, click Next.
  4. When the Is the hardware connected? dialog box appears, click Yes, I have already connected the hardware, and then click Next.
  5. In the Installed hardware list, click Add a new hardware device, and then click Next.
  6. In the What do you want the wizard to do? list, click Install the hardware that I manually select from a list (Advanced), and then click Next.
  7. In the Common hardware types list, click Network adapters, and then click Next.
  8. In the Manufacturer list, click Microsoft.
  9. In the Network Adapter list, click Microsoft Loopback Adapter, and then click Next twice.
  10. If a message about driver signing appears, click Continue Anyway.
  11. In the Completing the Add Hardware Wizard dialog box, click Finish, and then click OK.

To assign Loopback Adaptor and corresponding IP to each VPC

After you installed the Loopback Adaptor, you should see a new network connection in "Network Connections" screen of the host computer. Right-click on the Loopback Adapator network connection and select "Properties". In the "Microsoft Loopback Adapter Properties" dialog box, verify that the "Virtual Machine Network services" check box is selected. Now the VPCs can be assigned this adaptor in VIrtual PC settings.

  1. Start Virtual PC 2007.
  2. Right-click on your target VPC and click "Settings".
  3. In the "Settings" dialog box, select "Networking" in the "Settings" list, then select "Microsoft Loopback Adaptor" for the network adaptor. (I would suggest assigning the second network adaptor to Loopback Adaptor as we want to reserve the first one for "Shared networking NAT")
  4. For assigning IP, just treat it like other physical network and set the appropriate IP and netmask. Leave the Default gatway blank for the Virtual network

Configure firewall and test the network

At this point each VPCs should be able to "see" and ping others and the host. However the firewall settings on them may block the connection. You can disable windows firewall for the Loopback Adaptor to solve this problem:

  1. On your host computer, go to "Windows Firewall"
  2. Select "Advanced"
  3. Uncheck the network connection (in this case, the "VPC Virtual Network") that you don't want firewall to monitor.
  4. Click "OK".
  5. Repeat 1~4 on every VPCs.

blog170520091

2009年4月7日星期二

Writing, Starting and Stopping Linux daemon (w/ start-stop-daemon)

Overview

The first page written by Devin Watson shows a tutorial on how-to write a daemon (with an example). The second one at Tony's Cafe shows how to write scripts for Debian Linux to run the daemon. The last one is the Manpage of "start-stop-daemon" program.

Reference

Linux Daemon Writing HOWTO

Creating a Daemon in Debian Linux

Manpage of START-STOP-DAEMON

U-Boot related documentation

Overview

I have been fighting with embedded Linux system for the past two months, here is what I found when the card crash and I have to flash the Kernel.

Reference

U-Boot bootloader Wiki (Gumstix)

U-Boot Environment Variables

Some JavaScript / AJAX Resources

Overview

Including Script.aculo.us and others scripts.

Reference

20 Top Script.aculo.us Scripts you can’t live without

80 AJAX solutions that are excellent and useful

70 New, Useful AJAX And JavaScript Techniques

Concurrent remote desktop sessions in Windows XP sp3

Overview

This is a hack for allowing concurrent remote desktop sessions in Windows XP sp3

Reference

Concurrent Remote Desktop Sessions in Windows XP SP2

Enabling Concurrent Remote Desktop Sessions on Windows XP SP3 - Patched file included

2009年2月14日星期六

Cannot view the contents of a (.chm) file

Overview

I just get an e-book and find that all of the pages are dead. With some searching I find that the file is blocked by windows.

The solution is to unlock the .chm file. To do this:

  1. Right-click on the .chm file, select "Properties"
  2. Click "unlock"
  3. Done!

Reference

解决打开CHM格式文件出现“网页不能浏览”错误的方法

You cannot open HTML Help files....

2009年2月5日星期四

Add a select / deselect all checkbox to an ASP.NET checkbox list control

Overview

The code below demonstrate how to use JavaScript to get all the checkbox elements of a particular checkbox list, and then check / unchecked them base on the status of another checkbox (the sender).

This technique is also useful when you want to do other operation (e.g. ensure single selection) to all checkboxes of a checkbox list.

Reference

Check/Uncheck all items in a CheckBoxList using ASP.NET and Javascript

Code Snippet

This code is directly copied from Check/Uncheck all items in a CheckBoxList using ASP.NET and Javascript

function CheckBoxListSelect(cbControl, state)

{  

    var chkBoxList = document.getElementById(cbControl);

    var chkBoxCount= chkBoxList.getElementsByTagName("input");

    for(var i=0;i<chkBoxCount.length;i++)

    {

        chkBoxCount[i].checked = state;

    }

 

    return false;

}

2009年2月3日星期二

Multi-line Text boxes (Text area) behave incorrectly with Default Button in Firefox

Overview

I open form with a default button and a Multi-line ASP.NET text box (text area) in Firefox 3. When I hit "Enter" key in the text area, I expect the text area to start a new line. However, the default button is triggered.

Reference

Multiline Textboxes and DefaultButton in Firefox

2009年1月21日星期三

Restrict date range in Calendar

Overview

By default, Calendar control won't allow you to restrict the selectable date range. However, we can achieve this by doing two things:

  1. Restrict user from navigating to a month outside the range
  2. Restrict user from selecting a day outside the range

Reference

Visual Studio .NET - restrict date range in Calendar - eggheadcafe

Disable calendar day select link - eggheadcafe

Steps

Restrict user from navigating to a month outside the range

To achieve this, we can set the "NextMonthText" and "PrevMonthText" fields of the Calendar control to hide the link navigating to next or previous month.

Code Snippet:

protected void Cal_PreRender(object sender, EventArgs e)

        {

 

            if (Cal.VisibleDate.Year > 2009 || (Cal.VisibleDate.Year == 2009 && Cal.VisibleDate.Month >= 12))

            {

                Cal.NextMonthText = string.Empty;

            }

            else

            {

                Cal.NextMonthText = ">";

            }

 

            if (Cal.VisibleDate.Year < 2000 || (Cal.VisibleDate.Year == 2000 && Cal.VisibleDate.Month <= 1))

            {

                Cal.PrevMonthText = string.Empty;

            }

            else

            {

                Cal.PrevMonthText = "<";

            }

        }

Restrict user from selecting a day outside the range

This can be achieved by controlling the "IsSelectable" field in the "onDayRender" event handler of the Calendar.

Code Snippet:

protected void Cal_DayRender(object sender, DayRenderEventArgs e)

        {

            if (e.Day.Date.Year == 2009)

            {

                e.Day.IsSelectable = false;

            }

        }

ListView Control vs Repeater Control

Overview

Repeater control is one of my favorite ASP.NET controls because of its flexibility in UI design. However it lack some useful functions like "Sorting", "Paging" & "Data modification".

Now in ASP.NET 3.5 we have a ListView control which seems to do all of the Repeater's jobs and more. Below are some article talking about ListView control.

Reference

The asp:ListView control (Part 1) - Scott Guthrie

The ListView Dominates The Repeater - SingingEels

ListView Web Server Control Overview - MSDN