Insert Javascripts in your content of joomla

To put javascript in your content of joomla, just turn the WYSIWYG editor off. Admin > Global configuration > Wysiwyg editor > choose ‘No WYSIWYG editor’. You can then paste your code into the window. Same goes for any other scripts, such as embedding flash, quicktime etc.

My notes: about XML nodes, XmlNode.InnerText and XmlNode.InnerXml

XmlNode.InnerText Property :  Gets or sets the concatenated values of the node and all its child nodes.

The concatenated values of the node and all its child nodes.

Setting this property replaces all the child nodes with the parsed contents of the given string.

For leaf nodes, InnerText returns the same content as the Value property.

This property is a Microsoft extension to the Document Object Model (DOM).

The following example compares the InnerText and InnerXml properties.

using System;
using System.Xml;
public class Test {

public static void Main() {
XmlDocument doc = new XmlDocument();
doc.LoadXml(“<root>”+
“<elem>some text<child/>more text</elem>” +
“</root>”);

XmlNode elem = doc.DocumentElement.FirstChild;

// Note that InnerText does not include the markup.
Console.WriteLine(“Display the InnerText of the element…”);
Console.WriteLine( elem.InnerText );

// InnerXml includes the markup of the element.
Console.WriteLine(“Display the InnerXml of the element…”);
Console.WriteLine(elem.InnerXml);

// Set InnerText to a string that includes markup.
// The markup is escaped.
elem.InnerText = “Text containing <markup/> will have char(<) and char(>) escaped.”;
Console.WriteLine( elem.OuterXml );

// Set InnerXml to a string that includes markup.
// The markup is not escaped.
elem.InnerXml = “Text containing <markup/>.”;
Console.WriteLine( elem.OuterXml );
}
}

XmlNode.InnerXml Property : Gets or sets the markup representing only the child nodes of this node.

XmlNode.OuterXml Property : Gets the markup representing this node and all its child nodes.

Property Value
The markup containing this node and all its child nodes.

NoteNote:OuterXml does not return default attributes.

RemarksRemarks
This property is a Microsoft extension to the Document Object Model (DOM).

ExampleExample

The following example compares output from the InnerXml and OuterXml properties.

using System;
using System.IO;
using System.Xml;

public class Sample {

public static void Main() {

XmlDocument doc = new XmlDocument();
doc.LoadXml(“<book genre=’novel’ ISBN=’1-861001-57-5′>” +
“<title>Pride And Prejudice</title>” +
“</book>”);

XmlNode root = doc.DocumentElement;

// OuterXml includes the markup of current node.
Console.WriteLine(“Display the OuterXml property…”);
Console.WriteLine(root.OuterXml);

// InnerXml does not include the markup of the current node.
// As a result, the attributes are not displayed.
Console.WriteLine();
Console.WriteLine(“Display the InnerXml property…”);
Console.WriteLine(root.InnerXml);

}
}

——————————————————————
CreateElement:

using System;
using System.IO;
using System.Xml;

public class Sample {

public static void Main() {

// Create the XmlDocument.
XmlDocument doc = new XmlDocument();
string xmlData = “<book xmlns:bk=’urn:samples’></book>”;

doc.Load(new StringReader(xmlData));

// Create a new element and add it to the document.
XmlElement elem = doc.CreateElement(“bk”, “genre”, “urn:samples”);
elem.InnerText = “fantasy”;
doc.DocumentElement.AppendChild(elem);

Console.WriteLine(“Display the modified XML…”);
doc.Save(Console.Out);

}
}

CreateTextNode :

using System;
using System.IO;
using System.Xml;

public class Sample
{
public static void Main()
{
//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml(“<book genre=’novel’ ISBN=’1-861001-57-5′>” +
“<title>Pride And Prejudice</title>” +
“</book>”);

//Create a new node and add it to the document.
//The text node is the content of the price element.
XmlElement elem = doc.CreateElement(“price”);
XmlText text = doc.CreateTextNode(“19.95”);
doc.DocumentElement.AppendChild(elem);
doc.DocumentElement.LastChild.AppendChild(text);

Console.WriteLine(“Display the modified XML…”);
doc.Save(Console.Out);

}
}

XPath models an XML document as a tree of nodes. There are different types of nodes, including element nodes, attribute nodes and text nodes.

Here are some examples of location paths using the unabbreviated syntax:

*

child::para selects the para element children of the context node
*

child::* selects all element children of the context node
*

child::text() selects all text node children of the context node
*

child::node() selects all the children of the context node, whatever their node type
*

attribute::name selects the name attribute of the context node
*

attribute::* selects all the attributes of the context node
*

descendant::para selects the para element descendants of the context node
*

ancestor::div selects all div ancestors of the context node
*

ancestor-or-self::div selects the div ancestors of the context node and, if the context node is a div element, the context node as well
*

descendant-or-self::para selects the para element descendants of the context node and, if the context node is a para element, the context node as well
*

self::para selects the context node if it is a para element, and otherwise selects nothing
*

child::chapter/descendant::para selects the para element descendants of the chapter element children of the context node
*

child::*/child::para selects all para grandchildren of the context node
*

/ selects the document root (which is always the parent of the document element)
*

/descendant::para selects all the para elements in the same document as the context node
*

/descendant::olist/child::item selects all the item elements that have an olist parent and that are in the same document as the context node
*

child::para[position()=1] selects the first para child of the context node
*

child::para[position()=last()] selects the last para child of the context node
*

child::para[position()=last()-1] selects the last but one para child of the context node
*

child::para[position()>1] selects all the para children of the context node other than the first para child of the context node
*

following-sibling::chapter[position()=1] selects the next chapter sibling of the context node
*

preceding-sibling::chapter[position()=1] selects the previous chapter sibling of the context node
*

/descendant::figure[position()=42] selects the forty-second figure element in the document
*

/child::doc/child::chapter[position()=5]/child::section[position()=2] selects the second section of the fifth chapter of the doc document element
*

child::para[attribute::type=”warning”] selects all para children of the context node that have a type attribute with value warning
*

child::para[attribute::type=’warning’][position()=5] selects the fifth para child of the context node that has a type attribute with value warning
*

child::para[position()=5][attribute::type=”warning”] selects the fifth para child of the context node if that child has a type attribute with value warning
*

child::chapter[child::title=’Introduction’] selects the chapter children of the context node that have one or more title children with string-value equal to Introduction
*

child::chapter[child::title] selects the chapter children of the context node that have one or more title children
*

child::*[self::chapter or self::appendix] selects the chapter and appendix children of the context node
*

child::*[self::chapter or self::appendix][position()=last()] selects the last chapter or appendix child of the context node


Nodes and the Hierarchical Tree Structures They Comprise

Every component of an HTML code in a web page is a Node, or a leaf/branch if you look at it from the tree-like hierarchical point of view. A node can be of either of the following two types: an Element Node or a Text Node.

Element Nodes

Element nodes are tags encompassed in angled brackets. A good example would be XML/HTML elements such the paragraph tag <p>, image tag <img> etc. Element nodes can contain child nodes and attributes within them.

Text Nodes

Text nodes are simply strings of text. They can’t contain child nodes or attributes.

Let’s take a look at the following example:

<p>DOM</p>

This short line of code is comprised of two nodes: the paragraph element node, and the “DOM” text node. Since the text node is inside the element node it is its child.

If we take a look at its hierarchical structure it would look like this:

<p> (element node, parent node of “DOM”)
|
|
DOM (text node, child node of <p>)

And how about this line of code:

<p><b>DOM</b></p>

Here we have an additional element node, the HTML Bold tag <b>. Since this element is placed inside the paragraph element it is its child. The “DOM” text is now encapsulated inside the bold tag so it is the child of the <b> element node:

<p> (element node, parent node of <b>)
|
|
<b> (element node, child node of <p>, parent node of “DOM”)
|
|
DOM (text node, child node of <b>)

Let’s complicate things even more:

<p>This is a <b>DOM</b> Tutorial</p>

Now we still have the same two element nodes, but now we have three text nodes:

The bold tag as well as the two text nodes “This is a” and “Tutorial” are the children of the paragraph tag:

<p> (element node, parent node of <b>, “This is a”, and “Tutorial”)
|
|
+—+———————-+———————-+
|                  |               |
|              |               |
This is a (text node,       <b> (element node,     Tutorial (text node,
child node of <p>)  |  child node of <p>,           child node
|  parent node of <p>)            of <p>)
|
DOM (text node,
child node of <b>)

Node Properties

The two most common properties of nodes are the nodeName and nodeValue:

NodeName The name value of Element nodes is the name of the tag: <img>,<b> etc. The name value of “text” nodes is just “text”.

NodeValue The value for Text Nodes is the actual string of text. Element nodes don t have a value and this property is set to Null.

——————————————
The next example uses the following data.

<?access-control allow=”*”?>
<r>
<ch1/>
<ch2/>

</r>

Prior to revision 3, the document root element (r) is considered to have just two children: the element nodes with nodeNames “ch1” and “ch2”. In revision 3 and later, the document root element has five children:

1. The text node for the new line and spaces between the root element and the element node with nodeName “ch1”.
2. The element node with nodeName “ch1”.
3. The text node for the new line and spaces between the element node with nodeName “ch1” and the element node with nodeName “ch2”.
4. The element node with nodeName “ch2”.
5. The text node for the two new lines between the element node with nodeName “ch2” and the closing tag of the root element.

————————————————————————————-
What is the difference between XmlNode.InnerText and XmlNode.InnerXml

InnerXml serializes all child nodes so you get the markup for those
child nodes e.g. if you have
<gods><god><name>Kibo</name></god><gods>
and you access the InnerXml of the DocumentElement you get
<god><name>Kibo</name></god>
InnerText concatenates the text content of all text nodes contained so
in the above case InnerText of the DocumentElement gives you
Kibo

Note that followup is set to microsoft.public.dotnet.xml.

—————————————————————
function makeScrollableTable(tbl){
var pNode, w, hdr;

pNode = tbl.parentNode;
w = document.createElement(‘<SPAN style=”height:500px; overflow:
auto;”>’);
pNode.insertBefore(w, tbl);
w.appendChild(tbl);

for (var i=0; i < tbl.tHead.rows.length;
i++)    setRowWidth(tbl.tHead.rows[i].cells);
setRowWidth(tbl.tBodies(0).rows[0].cells);

hdr = tbl.cloneNode(false);
hdr.id += ‘Header’;
hdr.appendChild(tbl.tHead.cloneNode(true));
tbl.tHead.style.display = ‘none’;
pNode.insertBefore(hdr, w);
w.style.width = w.clientWidth + 50;

w2 = document.createElement(‘<table border=0 cellspacing=0
cellpadding=0 id=”‘ + tbl.id + ‘”>’);
w2.id = tbl.id + ‘Wrapper’;
pNode.insertBefore(w2, hdr);

w2.insertRow().insertCell().appendChild(hdr);
w2.insertRow().insertCell().appendChild(w);

w2.align = tbl.align;
tbl.align = hdr.align = ‘left’;
hdr.style.borderBottom = tbl.style.borderTop = ‘medium none’;
}

function setRowWidth(r){
var c;
for (var i=0; i < r.length; i++){
c = r[i];
c.width = c.clientWidth – parseInt(c.currentStyle.paddingLeft) –
parseInt(c.currentStyle.paddingRight);
}
}

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>