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

dt = dbDA.DB_GetTitle(“TREASURERTITLE”)

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”)))
Next
‘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
Return
End If
Else
Me.lblError.Text = “Can not find the configration of template file path!”
Me.lblError.ForeColor = Color.Red
Return
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.Clear()
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
memStreamTargetFile.Close()
End If

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

Response.End()
Else
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

Try
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
Next

pnl.Enabled = True
Catch ex As Threading.ThreadAbortException
Catch ex As Exception
Try
cnnstr = conn.GetConnectionString(DBTypes.LMS)
exHandler.ER_InsertError(cnnstr, System.Environment.UserName(), “LoansODR”, “DebentureDocsGen.aspx.vb”, “ChangeChildrenControlsStatus”, “System”, “1”, ex.StackTrace, ex.Message)
Catch
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
Try

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
Try
cnnstr = conn.GetConnectionString(DBTypes.LMS)
exHandler.ER_InsertError(cnnstr, System.Environment.UserName(), “LoansODR”, “DebentureDocsGen.aspx.vb”, “GetDateInWords”, “System”, “1”, ex.StackTrace, ex.Message)
Catch
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
Try
If inDateTime.Day > 0 And inDateTime.Day < 15 Then
Return inDateTime.AddMonths(months).AddDays(0 – inDateTime.Day + 1)
Else
Return inDateTime.AddMonths(months).AddDays(0 – inDateTime.Day + 15)
End If
Catch ex As Threading.ThreadAbortException
Catch ex As Exception
Try
cnnstr = conn.GetConnectionString(DBTypes.LMS)
exHandler.ER_InsertError(cnnstr, System.Environment.UserName(), “LoansODR”, “DebentureDocsGen.aspx.vb”, “Get1stOr15thDate”, “System”, “1”, ex.StackTrace, ex.Message)
Catch
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
Try
If inDateTime.Day > 0 And inDateTime.Day < 15 Then
Return inDateTime.AddMonths(months).AddDays(0 – inDateTime.Day + 1).Day.ToString + “st”
Else
Return inDateTime.AddMonths(months).AddDays(0 – inDateTime.Day + 15).Day.ToString + “th”
End If
Catch ex As Threading.ThreadAbortException
Catch ex As Exception
Try
cnnstr = conn.GetConnectionString(DBTypes.LMS)
exHandler.ER_InsertError(cnnstr, System.Environment.UserName(), “LoansODR”, “DebentureDocsGen.aspx.vb”, “Get1stOr15thDayString”, “System”, “1”, ex.StackTrace, ex.Message)
Catch
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;
else
{
//theNextBusinessDate = StartDate.AddDays(DurationBusinessDays);

//resultBusinessDate = StartDate;

if(DurationBusinessDays > 0)
{
do
{
resultBusinessDate = StartDate.AddDays(1);
if(IsBusinessDay(resultBusinessDate))
c++;
StartDate = resultBusinessDate;
}
while (c < (int)(Math.Abs(DurationBusinessDays)));
}
else
{
do
{
resultBusinessDate = StartDate.AddDays(-1);
if(IsBusinessDay(resultBusinessDate))
c++;
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;
}
else
{
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;

try
{
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”);
conn.Open();
sqlDS = new DataSet();
sqlDA = new SqlDataAdapter(sqlCmd);
sqlDA.Fill(sqlDS);

//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
break;
}
}
*/
//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

}
else
retV = false;
}
catch(System.Exception objexc)
{
throw objexc;
}
finally
{
sqlDS.Dispose();
sqlDA.Dispose();
sqlCmd.Dispose();
conn.Close();
conn.Dispose();
conn = null;
oConn = null;

}

return retV;
}

Store Procedure:

procGetHolidayList:

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

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

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

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

9: 2 small functions about data storing

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

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

Intro: a good utility for bulk renaming files

Bulk Rename Utility

Introduction

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:  http://www.bulkrenameutility.co.uk/Main_Intro.php

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


some websites collection

www.btalk.net (Home Business/Small Business Talking Forum)
www.canada365.net
www.hoocool.com (hosting, domain name, email…)
www.gogocoo.com (hosting, domain name, email…)
www.shopping4adult.com (Adult)
www.music4free.info (music downloads)
www.hknconsulting.com ( this is a demo and customer’s , not my own business)
www.wtime.mobi (mobile service)
www.eeee.ca (forum)
www.sametopic.com
www.0991.mobi
www.0691.mobi

Move local ASP.NET website based on MS Small business starter kit to Godaddy.com 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 Godaddy.com 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 (www.HKNConsulting.com):

1: use sql server 2005 management express to general SQL Scripit (get empty tables and asp.net 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 asp.net 2.0 tables:

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

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)

Go

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

<add name=”MFSQLConnectionString” connectionString=”Server=p3swhsql-vxx.xxx.xxx.secureserver.net;
Database=DB_<XXXXXX>;
User ID=<XXXXX>;
Password=<XXXX>;
Trusted_Connection=False”
providerName=”System.Data.SqlClient” />

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

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

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

PublicKeyToken=b03f5f7f11d50a3a”
connectionStringName=”MFSQLConnectionString”
enablePasswordRetrieval=”false”
enablePasswordReset=”true”
requiresQuestionAndAnswer=”true”
applicationName=”/”
requiresUniqueEmail=”false”
passwordFormat=”Hashed”
maxInvalidPasswordAttempts=”5″
minRequiredPasswordLength=”6″
minRequiredNonalphanumericCharacters=”0″
passwordAttemptWindow=”10″
passwordStrengthRegularExpression=””/>
</providers>
</membership>
<profile>
<providers>
<remove name=”AspNetSqlProfileProvider”/>
<add name=”AspNetSqlProfileProvider”
connectionStringName=”MFSQLConnectionString”
applicationName=”/”
type=”System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral,

PublicKeyToken=b03f5f7f11d50a3a”/>
</providers>
</profile>
<roleManager enabled=”true”>
<providers>
<remove name=”AspNetSqlRoleProvider”/>
<add name=”AspNetSqlRoleProvider”
connectionStringName=”MFSQLConnectionString”
applicationName=”/”
type=”System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral,

PublicKeyToken=b03f5f7f11d50a3a”/>
</providers>
</roleManager>

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

Files\root\799f60bd\464de44c\assembly\dl3\22c56c35\5400338b_b386c701\App_Code.DLL’

Cause:

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.

10:

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>
Reason:

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

Resolve:

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” DataSourceID=”ObjectDataSource1″
AllowPaging=”True” PageSize=”5″ OnRowCreated=”GridView1_RowCreated” BorderWidth=”0px”
BorderColor=”White” DataKeyNames=”serviceID”>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<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” />
<h2>
<asp:LinkButton ID=”LinkButton1″  CommandName= “Select” CommandArgument='<%#”Id”%>’
runat=”server” OnCommand=”LinkButton1_OnCommand”>
<%# Eval(“title”).ToString()%>
</asp:LinkButton></h2>
<p>
<%# Eval(“description”).ToString().PadRight(256,’ ‘).Substring(0, 256) %>
</p>
<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 />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings Mode=”NumericFirstLast” Position=”TopAndBottom” />
</asp:GridView>

11:

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

http://help.godaddy.com/article.php?article_id=59

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.
Resolve:

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 Godaddy.com 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 {
border:none;
}

.photo-border {
border:1px solid #cecece;
padding:4px;
background:#d9d9d9 url(../../images/bg-photo.png) top repeat-x;
margin-bottom:5px;
display:block;
}

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 {
float:left;
margin-right:10px;
}

.photo-float-right {
float:right;
margin-left:5px;
}

ASP.NET and XHTML

Why XHTML ?

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.

http://msdn2.microsoft.com/en-us/library/exc57y7e(vs.80).aspx

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.(http://www.w3.org/)

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.

<system.web>
<!– other elements here –>
<xhtmlConformance
mode=”Legacy” />
</system.web>

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

<system.web>
<!– other elements here –>
<xhtmlConformance
mode=”Strict” />
</system.web>

—————————————————–
Other ways:

http://www.charon.co.uk/content.aspx?CategoryID=28&ArticleID=53

Redirecting to an ASP.NET Mobile Web Page

(from: http://msdn2.microsoft.com/en-us/library/fhhycabe.aspx)

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.

C#
<script runat="server" language="c#">
    public void Page_Load(Object sender, EventArgs e) 
    {
        if (Request.Browser["IsMobileDevice"] == "true" ) 
        {
            Response.Redirect("MobileDefault.aspx");
        }
        else 
        {
            Response.Redirect("DesktopDefault.aspx");
        }
    }
</script>

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.

<configuration>
  <system.web>
    <httpRuntime useFullyQualifiedRedirectUrl = "true" />
  </system.web>
</configuration>

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.

Done!

Call Client-Side Script

RegisterStartupScript

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;”;
Page.RegisterStartupScript(“regJSval”,jScriptValidator);
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;
&amp;lt;script&amp;gt;

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

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

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

RegisterClientScriptBlock

Suppose
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;”;
Page.RegisterClientScriptBlock(“keyClientBlock”,jScript);
lblSequencial.Text=”Remaining part of the code executed”;
}

(from : http://www.codeproject.com/aspnet/ClientServer.asp )