Coding notes in my daily works (ASP.NET 1.1)

Here is some notes that recorded by myself when I work daily. They are about ASP.NET 1.1, maybe some of them can be re-used in ASP.NET 2.0 too.

1: Using “New ListItem” to Feed DropDownList Controller


If (Not dt Is Nothing) And (dt.Rows.Count > 0) Then
With dt
For intCounter = 0 To .Rows.Count – 1
Me.ddlTreasurerTitle.Items.Add(New ListItem(.Rows(intCounter).Item(“StatusShortDesc”).ToString, .Rows(intCounter).Item(“StatusCode”)))
‘Me.ddlTreasurerTitle.Items.FindByText(“Treasurer”).Selected = True
End With
End If

2: Finding a appSettings key in web.config file

If Array.IndexOf(ConfigurationSettings.AppSettings.AllKeys, “DocTemplatesPath”) > -1 Then
strTemplateFileNameWithPath = ConfigurationSettings.AppSettings(“DocTemplatesPath”) & strTemplateFileName
If Not (File.Exists(strTemplateFileNameWithPath)) Then
Me.lblError.Text = “No template found for selected document!”
Me.lblError.ForeColor = Color.Red
End If
Me.lblError.Text = “Can not find the configration of template file path!”
Me.lblError.ForeColor = Color.Red
End If

3: Using Memory to save a file:

Dim memStreamTargetFile As MemoryStream = New MemoryStream
Dim dbDocObj As New DocGenXML.WordXMLGen

If dbDocObj.ReplaceTextDueToDataArray_Stream(dataArray, strTemplateFileNameWithPath, nameSpaceURI, memStreamTargetFile) = True Then
Response.AddHeader(“Content-Disposition”, “attachment; filename=” & tmpTargetFileName)
Response.AddHeader(“Content-Length”, memStreamTargetFile.Length.ToString())
Response.ContentType = “application/octet-stream”

Dim byt As Byte() = memStreamTargetFile.ToArray()

If Not IsNothing(memStreamTargetFile) Then
End If

Response.OutputStream.Write(byt, 0, byt.Length)

lblError.Text = “Error: ” + “Generating document failed!”
lblError.ForeColor = Color.Red
End If

4: Enable or Disable all child controllers in a panel:

Private Sub ChangeChildrenControlsStatus(ByVal pnl As System.Web.UI.WebControls.Panel, ByVal enableStatus As Boolean)
Dim childControl As Control
‘Dim childControl As WebControl

For Each childControl In pnl.Controls
‘CType(childControl, WebControl).Enabled = True
Select Case childControl.GetType().ToString()
Case GetType(System.Web.UI.WebControls.TextBox).ToString()
CType(childControl, System.Web.UI.WebControls.TextBox).Enabled = enableStatus
Case GetType(System.Web.UI.WebControls.Button).ToString()
CType(childControl, System.Web.UI.WebControls.Button).Enabled = enableStatus
Case GetType(System.Web.UI.WebControls.DropDownList).ToString()
CType(childControl, System.Web.UI.WebControls.DropDownList).Enabled = enableStatus
Case GetType(System.Web.UI.WebControls.RequiredFieldValidator).ToString()
CType(childControl, System.Web.UI.WebControls.RequiredFieldValidator).Enabled = enableStatus
Case GetType(System.Web.UI.WebControls.RegularExpressionValidator).ToString()
CType(childControl, System.Web.UI.WebControls.RegularExpressionValidator).Enabled = enableStatus
Case GetType(System.Web.UI.WebControls.RangeValidator).ToString()
CType(childControl, System.Web.UI.WebControls.RangeValidator).Enabled = enableStatus
Case GetType(System.Web.UI.WebControls.CompareValidator).ToString()
CType(childControl, System.Web.UI.WebControls.CompareValidator).Enabled = enableStatus
Case GetType(System.Web.UI.WebControls.Label).ToString()
CType(childControl, System.Web.UI.WebControls.Label).Enabled = enableStatus
Case GetType(System.Web.UI.WebControls.CheckBox).ToString()
CType(childControl, System.Web.UI.WebControls.CheckBox).Enabled = enableStatus

End Select

pnl.Enabled = True
Catch ex As Threading.ThreadAbortException
Catch ex As Exception
cnnstr = conn.GetConnectionString(DBTypes.LMS)
exHandler.ER_InsertError(cnnstr, System.Environment.UserName(), “LoansODR”, “DebentureDocsGen.aspx.vb”, “ChangeChildrenControlsStatus”, “System”, “1”, ex.StackTrace, ex.Message)
End Try

5: Getting a date in its words format

for example: the 1st day of July, 2007

Public Function GetDateInWords(ByVal inDateTime As DateTime) As String
Dim strDaySuffix As String

Select Case inDateTime.Day
Case 1, 21, 31
strDaySuffix = “st”
Case 2, 22
strDaySuffix = “nd”
Case 3, 23
strDaySuffix = “rd”
Case Else
strDaySuffix = “th”
End Select

Return (“the ” & inDateTime.Day.ToString() & strDaySuffix & ” day of ” & inDateTime.ToString(“MMMM, yyyy”))

Catch ex As Threading.ThreadAbortException
Catch ex As Exception
cnnstr = conn.GetConnectionString(DBTypes.LMS)
exHandler.ER_InsertError(cnnstr, System.Environment.UserName(), “LoansODR”, “DebentureDocsGen.aspx.vb”, “GetDateInWords”, “System”, “1”, ex.StackTrace, ex.Message)
End Try
Me.PublishException(New Ofa.Framework.Exceptions.GlobalException(ex.Message, ex), “DebentureDocsGen.GetDateInWords”)
End Try
End Function
Me.PublishException(New Ofa.Framework.Exceptions.GlobalException(ex.Message, ex), “DebentureDocsGen.ChangeChildrenControlsStatus”)
End Try
End Sub

6: if the day < 15, return date 1, else, return date 15

Public Function Get1stOr15thDate(ByVal inDateTime As DateTime, ByVal months As Integer) As Date
If inDateTime.Day > 0 And inDateTime.Day < 15 Then
Return inDateTime.AddMonths(months).AddDays(0 – inDateTime.Day + 1)
Return inDateTime.AddMonths(months).AddDays(0 – inDateTime.Day + 15)
End If
Catch ex As Threading.ThreadAbortException
Catch ex As Exception
cnnstr = conn.GetConnectionString(DBTypes.LMS)
exHandler.ER_InsertError(cnnstr, System.Environment.UserName(), “LoansODR”, “DebentureDocsGen.aspx.vb”, “Get1stOr15thDate”, “System”, “1”, ex.StackTrace, ex.Message)
End Try
Me.PublishException(New Ofa.Framework.Exceptions.GlobalException(ex.Message, ex), “DebentureDocsGen.Get1stOr15thDate”)
End Try
End Function

Public Function Get1stOr15thDayString(ByVal inDateTime As DateTime, ByVal months As Integer) As String
If inDateTime.Day > 0 And inDateTime.Day < 15 Then
Return inDateTime.AddMonths(months).AddDays(0 – inDateTime.Day + 1).Day.ToString + “st”
Return inDateTime.AddMonths(months).AddDays(0 – inDateTime.Day + 15).Day.ToString + “th”
End If
Catch ex As Threading.ThreadAbortException
Catch ex As Exception
cnnstr = conn.GetConnectionString(DBTypes.LMS)
exHandler.ER_InsertError(cnnstr, System.Environment.UserName(), “LoansODR”, “DebentureDocsGen.aspx.vb”, “Get1stOr15thDayString”, “System”, “1”, ex.StackTrace, ex.Message)
End Try
Me.PublishException(New Ofa.Framework.Exceptions.GlobalException(ex.Message, ex), “DebentureDocsGen.Get1stOr15thDayString”)
End Try
End Function

7: Using IndexOf to find a substring in a string:

strSelectedTemplateFileName = Me.lbDocList.SelectedItem.Value.Substring(Me.lbDocList.SelectedItem.Value.IndexOf(“_”, 0) + 1)
strSelectedTemplateFileName = strSelectedTemplateFileName.Substring(strSelectedTemplateFileName.IndexOf(“_”, 0) + 1)

8:  Getting the next N business days, N > 0 , N = 0, N < 0 :

Because holidays is always variable due to different country and different new policy. so we have to create a data table to store holidays, but , we don’t need to store weekends.

then I check the datatable to determine whether the day is in the holidays datable, and then, I caculate them using the following functions:

public static DateTime GetBusinessDate(DateTime StartDate, double DurationBusinessDays)
int c = 0;

DateTime resultBusinessDate;

if(DurationBusinessDays == 0)
resultBusinessDate = StartDate;
//theNextBusinessDate = StartDate.AddDays(DurationBusinessDays);

//resultBusinessDate = StartDate;

if(DurationBusinessDays > 0)
resultBusinessDate = StartDate.AddDays(1);
StartDate = resultBusinessDate;
while (c < (int)(Math.Abs(DurationBusinessDays)));
resultBusinessDate = StartDate.AddDays(-1);
StartDate = resultBusinessDate;
while (c < (int)(Math.Abs(DurationBusinessDays)));


return resultBusinessDate;

public static bool IsBusinessDay(DateTime dt)
if ((dt.DayOfWeek == DayOfWeek.Saturday) || (dt.DayOfWeek == DayOfWeek.Sunday) || (IsHoliday(dt)))
return false;
return true;

public static bool IsHoliday(DateTime dt)
LMSDataAccess.DataConnection oConn = null;
string strConString;
SqlConnection conn = null;
SqlCommand sqlCmd = null;
SqlDataAdapter sqlDA = null;
DataSet sqlDS = null;
//int i;
bool retV = false;
//DataRow[] drs = null;

oConn = new LMSDataAccess.DataConnection();
strConString = oConn.GetConnectionString((int)LMSDataAccess.DBTypes.LMS);
conn = new SqlConnection(strConString);
sqlCmd = new SqlCommand(“procGetHolidayList”, conn);
sqlCmd.CommandType = CommandType.StoredProcedure;
//sqlCmd.Parameters.Add(“@InDate”, InDate);
sqlCmd.Parameters.Add(“@CountryShortName1”, “CA”);
sqlDS = new DataSet();
sqlDA = new SqlDataAdapter(sqlCmd);

//for debug
//dt = new DateTime(2007,1,1);

if(sqlDS.Tables[0].Rows.Count > 0)
for(i=0; i<sqlDS.Tables[0].Rows.Count; i++)
if(dt == (DateTime)sqlDS.Tables[0].Rows[i][0])
retV = true;   //Is holiday
//drs = sqlDS.Tables[0].Select(“Author = ‘Name'”);
sqlDS.Tables[0].DefaultView.Sort=sqlDS.Tables[0].Columns[0].ColumnName+” asc”;
if(sqlDS.Tables[0].DefaultView.Find(dt) > 0)
retV = true;   //Is holiday

retV = false;
catch(System.Exception objexc)
throw objexc;
conn = null;
oConn = null;


return retV;

Store Procedure:



— Creation Date:     22 Jan 2007
— Author:
— Description:     Get the holidays list due to Country
— Tables:         CalDates
— Last Update:
ALTER    PROCEDURE dbo.procGetHolidayList
@CountryShortName1 varchar(2)= null

select CD.CalDate
from CalDates CD join CalLongNames CLN on CD.CalID = CLN.CalKey
where Deleted = 0 and ( CLN.CalShortName = @CountryShortName1 )


9: 2 small functions about data storing

Public Function ReturnDBNullWhenNonNumeric(ByVal Input As String) As Object
If IsNumeric(Input) Then
Return CType(Input, Decimal)
Return (DBNull.Value)
End If
End Function

Public Function ReturnZeroWhenNonNumeric(ByVal Input As String) As Decimal
If IsNumeric(Input) Then
Return CType(Input, Decimal)
Return (0)
End If
End Function

Intro: a good utility for bulk renaming files

Bulk Rename Utility


Bulk Rename Utility is a utility which allows you to easily rename files and directories, based upon extemely flexible criteria. Add date-stamps, replace numbers, insert strings, convert case, add auto-numbers, process folders and subfolders….plus loads more!

Official website:

There is no unicode version they provide. But a Chinese group made 2 chinese version: one unicode version, one ascii version:

some websites collection (Home Business/Small Business Talking Forum) (hosting, domain name, email…) (hosting, domain name, email…) (Adult) (music downloads) ( this is a demo and customer’s , not my own business) (mobile service) (forum)

Move local ASP.NET website based on MS Small business starter kit to hosting

I create an ASP.NET 2.0 small website for a company based on Microsoft  Small Business Starter Kit recently.

I added administration module, login module and other new module the customer required. When I finished, Everything work well on my local PC. Later the customer bought a share hosting space and I have to deploy the website to his godaddy space.

Since I developed this small website on SQL Server 2005 Express and MS Visual studio 2005 professional edition. I met a big problem : How to move the data from SQL Server 2005 Express to Godaddy’s SQL Server 2005 (I am lucky this time, Godaddy provides SQL Server 2005 since 2007 or the end of 2006, I bought its hosting in the beginning of 2006, it was only SQL Server 2000 and only there is ONE SQL server DB that customer can use).

Finally I deploy successfully. I write down all the processing that I did for this small website (

1: use sql server 2005 management express to general SQL Scripit (get empty tables and security tables, views,

store precedure), get a .sql file; (godaddy provides SQl Server 2005 now)

2: remove all “–” comment line from .sql file (godaddy’s SQl control panel doesn’t recognize “–” comment sign);

3: copy all sql script to godaddy’s sql server control panel and run;

4: insert some initial data to 2.0 tables:


INSERT INTO [aspnet_SchemaVersions]([Feature], [CompatibleSchemaVersion], [IsCurrentVersion])
VALUES(‘common’, 1, 1)

INSERT INTO [aspnet_SchemaVersions]([Feature], [CompatibleSchemaVersion], [IsCurrentVersion])
VALUES(‘health monitoring’, 1, 1)

INSERT INTO [aspnet_SchemaVersions]([Feature], [CompatibleSchemaVersion], [IsCurrentVersion])
VALUES(‘membership’, 1, 1)

INSERT INTO [aspnet_SchemaVersions]([Feature], [CompatibleSchemaVersion], [IsCurrentVersion])
VALUES(‘personalization’, 1, 1)

INSERT INTO [aspnet_SchemaVersions]([Feature], [CompatibleSchemaVersion], [IsCurrentVersion])
VALUES(‘profile’, 1, 1)

INSERT INTO [aspnet_SchemaVersions]([Feature], [CompatibleSchemaVersion], [IsCurrentVersion])
VALUES(‘role manager’, 1, 1)


5: modify web.config to give correct connect string:

<add name=”MFSQLConnectionString” connectionString=”;
User ID=<XXXXX>;
providerName=”System.Data.SqlClient” />

6: make sure in your web.config , there are some configration for 2.0 membership due to your own database (combine

the 2.0 membership database — normally it is ASPNETDB.mdf, to your own database):

<remove name=”AspNetSqlMembershipProvider”/>
<add name=”AspNetSqlMembershipProvider”
type=”System.Web.Security.SqlMembershipProvider, System.Web, Version=, Culture=neutral,

<remove name=”AspNetSqlProfileProvider”/>
<add name=”AspNetSqlProfileProvider”
type=”System.Web.Profile.SqlProfileProvider, System.Web, Version=, Culture=neutral,

<roleManager enabled=”true”>
<remove name=”AspNetSqlRoleProvider”/>
<add name=”AspNetSqlRoleProvider”
type=”System.Web.Security.SqlRoleProvider, System.Web, Version=, Culture=neutral,


7: Remove ”  <customErrors mode=”RemoteOnly” defaultRedirect=”CustomError.aspx”> from web.config file;
Add “<customErrors mode=”Off”/>”;

8: Insert your own data to your user tables:

INSERT INTO [Services]([visible], [title], [Category],[description])
VALUES(True, ‘Expertise on business’, ‘Business’,’•    Governments and public sectors
•    Banking business
•    Mutual funds investments
•    Group Pensions
•    Insurance

INSERT INTO [Services]([visible], [title], [Category],[description])
VALUES(True, ‘Expertise on Information Technologys’, ‘IT’,’•    e-Solutions using latest web technology
•    Infrastructure architecture
•    Enterprise Technology Assessments

INSERT INTO [Services]([visible], [title], [Category],[description])
VALUES(True, ‘Business Analysis’, ‘IT’,’•    Strategic planning
•    Business case development
•    Preliminary analysis and needs identification
•    Business requirement development
•    Business process development and re-design

INSERT INTO [Services]([visible], [title], [Category],[description])
VALUES(True, ‘System Design and Development’, ‘IT’,’•    Project Management
•    Requirements definition
•    System requirements definition
•    System architecture
•    Data and process analysis
•    Development and Implementation
•    Quality assurance and user acceptance testing
•    Documentation

INSERT INTO [Staff]([visible], [firstName],[lastName],[title],[description])
VALUES(True, ‘Wayne’, ‘Nguyen’,’Senior Team Manager’,’Wayne is a partner with HKN Consulting and supports the Ontario

Public Sector Practices.   Wayne brings over 15 years of financing industry and consulting experience both in the private

and public sectors.  Wayne has built a great deal of knowledge and experience in e-Government and e-Business through

managing projects for many major financing clients from agencies under Ontario Ministry of Finance, Ministry of Municipal

Affairs and Housing, to banking, investments, and insurance companies.  His extensive experience of back-end and web-based

technology as well as indepth knowledge in business processes and practices within and across organizations help him in

achieving high quality results for clients.

Prior to doing consulting, Wayne was project manager and technical lead for several companies, including Barclays Bank

(U.K.), Fidelity Investments (U.S.) , and Canada Life.  He holds a Master degree in Computer Science.’)

INSERT INTO [Staff]([visible], [firstName],[lastName],[title],[description])
VALUES(True, ‘Professional’, ‘Team’,’Professional Team’,’Our professional team consists of dedicated, highly trained and

experienced individuals:

•    Project managers
•    Applications architects
•    Business analysts
•    Quality assurance analysts
•    Systems analysts
•    Database analysts
•    Developers

INSERT INTO [Images]([fileName], [path],[imgClass])
VALUES(‘POINT.GIF’, ‘images\staff\’,’STAFF’)

INSERT INTO [Images]([fileName], [path],[imgClass])
VALUES(‘2190.jpg’, ‘images\services\’,’SERVICE’)

(Note: if you insert images into Image Table, you must check whether these images existing the related folder)

9: Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the

following specific error details and modify your source code appropriately.

Compiler Error Message: CS0433: The type ‘Staff’ exists in both ‘c:\windows\Microsoft.NET\Framework\v2.0.50727\Temporary

ASP.NET Files\root\799f60bd\464de44c\assembly\dl3\058d1167\5ec0b38b_b386c701\App_Web_75ma_t_n.DLL’ and

‘c:\windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET



I used the same name “Staff” for one aspx page and one class, this lead Type name conflict when compile, but it can work on

my local PC not only on Godaddy remote hosting, Finally I give the class name a new name “StaffType” , then it is OK.


Unable to cast object of type ‘System.DBNull’ to type ‘System.String’.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace

for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Unable to cast object of type ‘System.DBNull’ to type ‘System.String’.

Source Error:

Line 41:                         <asp:TemplateField>
Line 42:                             <ItemTemplate>
Line 43:                                 <asp:Image ID=”Image2″ runat=”server” ImageUrl='<%# (string)Eval(@”imageUrl”) +

(string)Eval(@”imgFileName”) %>’
Line 44:                                     AlternateText='<%# (string)Eval(“imageAltText”)%>’ Width=”120″ Height=”90″

CssClass=”photo-border photo-float-left” />
Line 45:                                 <h2>

imageAltText field is Null. strange it work on Local but No work on , just like 9 above.


<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” DataSourceID=”ObjectDataSource1″
AllowPaging=”True” PageSize=”5″ OnRowCreated=”GridView1_RowCreated” BorderWidth=”0px”
BorderColor=”White” DataKeyNames=”serviceID”>
<asp:Image ID=”Image2″ runat=”server” ImageUrl=‘<%# ((Eval(“imageUrl”) is DBNull)?String.Empty:(string)(Eval(@”imageUrl”))) + ((Eval(“imgFileName”) is DBNull)?String.Empty:(string)(Eval(@”imgFileName”))) %>’
AlternateText=‘<%# ((Eval(“imageAltText”) is DBNull)?String.Empty:(string)(Eval(“imageAltText”))) %>’ Width=”120″ Height=”90″ CssClass=”photo-border photo-float-left” />
<asp:LinkButton ID=”LinkButton1″  CommandName= “Select” CommandArgument='<%#”Id”%>’
runat=”server” OnCommand=”LinkButton1_OnCommand”>
<%# Eval(“title”).ToString()%>
<%# Eval(“description”).ToString().PadRight(256,’ ‘).Substring(0, 256) %>
<asp:ImageButton ID=”ImageButton1″ CommandName=”Select” CommandArgument='<%#”Id”%>’
runat=”server” OnCommand=”LinkButton1_OnCommand” ImageUrl=”images/arrow.gif” />
<asp:LinkButton ID=”LinkButtonNews” CommandName=”Select” CommandArgument='<%#”Id”%>’
runat=”server” OnCommand=”LinkButton1_OnCommand”>Read More </asp:LinkButton>
<hr />
<PagerSettings Mode=”NumericFirstLast” Position=”TopAndBottom” />


Administraton : When tried to upload image file, get the following error:

ERROR: Access to the path ‘d:\hosting\waynenguyen\images\staff\Blue hills.jpg’ is denied.

Reason: User Permissions

Keep in mind that with ASP hosting, the root directory of a hosting account will never have write access using an

ASP/ASP.NET script. If you want to specify write access to a subfolder, you must define write access to that folder through

the Directory Management option in your hosting account settings. The Directory Management settings are also used to set up

a “Virtual Root” in IIS by selecting the Set Root option.

should set user permissions for image/staff and image/services folder.

Since the hosting is windows hosting, so I can not set permission by FTP tool.

ONLY way:  set READ and WRITE permissions in control panel:

Directory Management -> click CREATE DIRECTORY button -> input “image/staff”, and check on “Write” and “Read” -> click

Continue button -> Click “Edit” button (Don’t click “ADD” button since the folder has already created when I use FTP)

How to make a border for a image using HTML

in CSS file:

img {

.photo-border {
border:1px solid #cecece;
background:#d9d9d9 url(../../images/bg-photo.png) top repeat-x;

in Code file:

<asp:Image ID=”Image1″ runat=”server” CssClass=”photo-float-left photo-border”  Height=”124px” ImageUrl=”~/images/homeStaff.JPG”   Width=”154px” />

How do I align an image to the right (or left) using HTML?

You can use <img align=”right”> to float a image to the right. (Use align=”left” to float it to the left.) Any content that follows the <img> tag will flow around the image. Use <br clear=”right”> or <br clear=”all”> to mark the end of the text that is to flow around the image, as shown in this example:

The image in this example will float to the right.

<img align=”right” src=… alt=…>

This text will wrap to fill the available space to the left of (and if the text is long enough, below) the image.

<br clear=”right”>

This text will appear below the image, even if there is additional room to its left.

The CSS float property can also be used:

.photo-float-left {

.photo-float-right {



XHTML is a World Wide Web Consortium (W3C) standard that defines HTML as an XML document. Creating Web pages that are conformant with XHTML standards has several advantages:

*      It guarantees that the elements in the pages are well formed.
*      Because many browsers are increasingly moving toward supporting XHTML, creating pages that conform to XHTML standards helps ensure that your pages render consistently in all browsers.
*      Using XHTML helps to make pages conform more readily to accessibility standards.
*      XHTML is extensible, allowing the definition of new elements.
*      An XHTML page is much easier to read programmatically for situations in which the Web page is processed by a computer instead of being read by users, and the document can be manipulated using transformations.

This page is specific to Microsoft Visual Studio 2005/.NET Framework 2.0

The W3C has identified several levels of XHTML conformance: XHTML 1.0 Transitional, XHTML 1.0 Frameset, XHTML 1.0 Strict, and XHTML 1.1. The XHTML 1.1 specification is the strictest of these levels.

For more information about the XHTML standard, see the specification for the Second Edition of XHTML 1.0 on the W3C Web site.(

How to: Configure XHTML Rendering in ASP.NET Web Sites

By default, when you are working with browsers that support at least HTML 4.0, ASP.NET pages and controls render markup that conforms to the XHTML 1.0 Transitional standard. However, you might want ASP.NET to render markup that conforms to the stricter XHTML 1.0 Strict specification. Conversely, you might want ASP.NET to render markup that does not conform to XHTML 1.0 Transitional specifications. This is typically true when you have existing pages that rely on tags or attributes that were supported in earlier versions of ASP.NET but do not conform to XHTML standards, such as rendering a name attribute in the form tag.

You can configure your Web site to render markup in three ways:

*   Legacy (which is similar to how markup was rendered in previous versions of ASP.NET)
*   Transitional (XHTML 1.0 Transitional)
*   Strict (XHTML 1.0 Strict)

Legacy is for render ASP.NET page markup that does not conform to XHTML, Transitional and Strict are for conforming ASP.NET pages to XHTML

o configure XHTML rendering in an ASP.NET Web site

Under the system.web element in your application’s Web.config file, add an xhtmlConformance element, and then set the mode attribute to Legacy, Transitional, or Strict. If no xhtmlConformance element is defined in the Web.config file, the default setting mode is transitional.

The following code example shows part of a Web.config file in which XHTML rendering is disabled.

<!– other elements here –>
mode=”Legacy” />

The following code example shows part of a Web.config file in which XHTML 1.0 Strict rendering is specified.

<!– other elements here –>
mode=”Strict” />

Other ways:

Redirecting to an ASP.NET Mobile Web Page


If you create an application that has one user interface optimized for a desktop browser and a second user interface optimized for mobile applications, you need a mechanism to redirect mobile device customers to the mobile Web pages.

Because some devices do not support cookies, consider whether you want to rely on cookies for your application. For more information, see Controlling Session State.

If your application does not use cookies, you can use the following code in a Microsoft ASP.NET site to redirect to an ASP.NET mobile Web application.

<script runat="server" language="c#">
    public void Page_Load(Object sender, EventArgs e) 
        if (Request.Browser["IsMobileDevice"] == "true" ) 

Because some devices do not accept relative URLs, you must also set the useFullyQualifiedRedirectUrl attribute of the <httpRuntime> element to true in the Web.config file. This sends a fully qualified URL to the client with the session ID appended to the end of the URL. Specifying a relative URL and then converting that URL to a fully qualified URL is necessary to preserve session state. The following example shows the configuration setting.

    <httpRuntime useFullyQualifiedRedirectUrl = "true" />

How to change Joomla root URL

If install Joomla on a remote hosting that can install multiple website, you should put all joomla files into a sub-folder, and install joomla database into a seperate database or a new database. and then maybe you have a seperate domain name for your new joomla website. You can setup all steps that just follow  regular steps that multiple websites installed into the same space and add a new domain name to point to your new sub-folder, normally, you should think your new website prepare to work; just one step left: change the root URL of your new website.

Now maybe you just prepare to do like what you did before – access into the database and try to find some field indicate the root URL, but, when you scan all and brower all database, you find you can not find a field store the value of root URL ! strange! where it is ? Joomla doesn’t use database to store its system root URL ?

Yes! Joomla really doesn’t use database store the root URL, it uses config file: in the root of your joomla website, you can find a file named “configuration.php”, open it and you will find the root URL – “$mosConfig_live_site”, change its value to your final root URL.


Call Client-Side Script


Using RegisterStartupScript we can write
JavaScript function in code behind and call it from code-behind or from
HTML. Look at the below code for reference.
Calling &amp; writing JavaScript function from server side code behind

private void Page_Load(object sender, System.EventArgs e)
string jScriptValidator;
jScriptValidator=”&amp;lt;script&amp;gt; function ReqFieldValidator()” +
” { if (document.forms[0].txtField.value == ”) \n”;
jScriptValidator+=”{ alert(‘TextBox cannot be empty’) \n “;
jScriptValidator+=”return false; \n”;
jScriptValidator+=”} \n”;
jScriptValidator+=” return true \n”;
jScriptValidator+=” } &amp;lt;/script&amp;gt;”;
btnSubmit.Attributes.Add(“onclick”,”return ReqFieldValidator()”);


Writing JavaScript function in server side code behind and calling from HTML

//Server side
private void Page_Load(object sender, System.EventArgs e)
string jScript;
jScript=”&amp;lt;script&amp;gt;function JavScriptFn(){alert” +
” (‘Client Function in javascript is call’)}&amp;lt;/script&amp;gt;”;

//HTML side
&amp;lt; A onclick=”JavScriptFn()” &amp;gt;
&amp;lt; asp:Label id=”Label1″ runat=”server” Width=”281px”
ForeColor=”#8080FF”&amp;gt;Click to call Javascript function.
&amp;lt;/asp:Label&amp;gt; &amp;gt;/A &amp;gt;

Writing JavaScript in HTML and calling it from code-behind

&amp;lt;Head &amp;gt;

function ReqField1Validator()
if (document.forms[0].txtField1.value == ”)
alert(‘TextBox cannot be empty’)
return false
return true

&amp;lt;/Head &amp;gt;

private void Page_Load(object sender, System.EventArgs e)
btnOK.Attributes.Add(“onclick”,”return ReqField1Validator()”);


we want JavaScript code to be executed but not a function. In that case
we make use of RegisterClientScriptBlock.RegisterClientScriptBlock
which helps to make server side code as well as client side code inline
to each other.

private void btnClientBlock_Click(object sender, System.EventArgs e)
string jScript;
jScript=”&amp;lt;script&amp;gt;alert (‘Javascript block of code executed’)&amp;lt;/script&amp;gt;”;
lblSequencial.Text=”Remaining part of the code executed”;

(from : )