Paypal STANDARD Website Payment Walkthrough?

Paypal STANDARD Website Payment Walkthrough?

Here is from a question about Commerce Starter Kit (asp.net). maybe it is can used for any e-commerce website code to setup Paypal payment.

Paypal STANDARD Website Payment Walkthrough?

To setup a fictitious Paypal account in the Sandbox and confirming the account:

1. Log into the Developer Central website at http://developer.paypal.com.
2. This will bring you to the Developer Central homepage.
3. Click on the Sandbox link found on the right side of the page or the tab found at the top.
4. This will list your fictious sandbox accounts.  To create a new one, click on Create Account.
5. When you click Create Account, it will open a new page of the Register a New Paypal account on the Sandbox environment.
6. You may select one of three account types (casual shoppers, casual sellers, or business owners)
7. For this example, let’s select casual shopper by clicking on the Start Now button
8. Enter in the pertinent information on the Create A Paypal account page and click on the “I Agree, Create My Account”.
9. This will take you to the Account Sign Up results page.
10. It now tells you to confirm your email address… Go back to the Developer Central page where the Sandbox tab is.  Make sure to click the tab again to refresh the list of test accounts with the new account showing up on the list!
11. Now… click on the Email tab found just two tabs to the right of the sandbox tab – this is where you will find all the email coming to the new fictitious email box.  You will see an email there with the subject Activate Your Paypal account.  Click the link of the “email”.
12. A fake email should popup on a new browser window – copy the confirmation number to the “clipboard”
13. Go back to the Sandbox tab, and select the new test account and click the Launch Sandbox button. Sign in to the sandbox with the new test account email address and password by clicking the Login button.
14. To the left you will see a link to “Confirm Email” – click it.
15. Then click the link… “Click here if a link DOES NOT appear in the email”
16. Paste the confirmation number (saved in the clipboard) into the field and click the Confirm button.
17. The account is NOW confirmed.  You may now click on Continue or Skip to do more setup for the account.

Hope this helps.

A button style HyperLink in ASP.NET

<asp:HyperLink ID=”linkCountry” runat=”server”
NavigateUrl='<%# “CountryLst.aspx?ContinentID=” + DataBinder.Eval(Container.DataItem,”continentid”) %>’
Text='<%# DataBinder.Eval(Container.DataItem, “continentname”) %>’
Font-Bold=”True” ForeColor=”Black” Font-Size=”Medium” BorderWidth=”3px” BackColor=”LightGray” BorderStyle=”Outset” Width=”83px” style=”TEXT-DECORATION: none”  >

Generating Client-Side Script for Postback

(from: http://msdn2.microsoft.com/en-us/library/aa720099(VS.71).aspx)

Only two HTML form elements (button and image button) cause form postback. If your custom control renders an HTML element that does not cause postback (such as a text box or a link button) and you want the control to initiate postback, you can program this in ASP.NET through an event architecture that relies on client-side script (JScript, JavaScript).

Control developers need to make a few small changes to their controls to enable this postback mechanism. The following code fragment shows (in bold) the code that must be added to the Render method of a control to initiate postback.

[C#]
protected override void Render(HtmlTextWriter output) {
                  output.Write("<a  id=\"" + this.UniqueID + "\" href=\"javascript:" + Page.GetPostBackEventReference(this) +"\">");
                  output.Write(" " + this.UniqueID + "</a>");
            }
[Visual Basic]
Protected Overrides Sub Render(output As HtmlTextWriter)
   output.Write("<a  id=""" & Me.UniqueID & _
         """ href=""javascript:" & _
         Page.GetPostBackEventReference(Me) & """>")
   output.Write(" " & Me.UniqueID & "</a>")
End Sub

The GetPostBackEventReference method emits client-side script that initiates postback and also provides a reference to the control that initiated the postback event.

To understand what the GetPostBackEventReference method does, compile the code in the next section, Postback Using Client-Side Script Sample, and request the accompanying .aspx page in your browser. If you view the source for the rendered page using your browser’s View Source command, you will see the following HTML and script. (The actual values of the name and the ID attributes of the form will differ, and so will the value attribute of the hidden variable.)

<html>
<body>
<form name="ctrl2" method="POST" action="MyLinkButton.aspx" id="ctrl2">
<input type="hidden" name="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" value="dDwtMjI1NTgwNDE2Ozs+eIZ+AfRvoCj1nWimbh+zPv/rKNg=" />                  
Here is the custom link button.<br>
<a  id ="Link" href="javascript:__doPostBack('Link','')"> Link</a> 
<br><br>
<input name="TextBox" type="text" value="Click the link" id="TextBox" style="background-color:Cyan;width:200px;" /> 
<br>                                                
<script language="javascript">
<!--
      function __doPostBack(eventTarget, eventArgument) {
            var theform = document.ctrl2
            theform.__EVENTTARGET.value = eventTarget
            theform.__EVENTARGUMENT.value = eventArgument
            theform.submit()
      }
// -->
</script>
</form>                  
</body>                        
</html>

The elements in bold in this example — two hidden fields and the client-side script method — are added by the ASP.NET page framework. The hidden form fields indicate which server control to post to and optionally specify an argument to pass. The client-side script method is used to set the hidden fields and causes the form to be submitted to the server. For a complete sample, see Postback Using Client-Side Script Sample.

See Also

Postback Using Client-Side Script Sample

Get relavated value of selected row of GridView using javascipts

(from: http://geekswithblogs.net/azamsharp/archive/2006/08/29/89697.aspx)
So, here is the story. I have a GridView which contains the ASP.NET CheckBox control. Each row also have the primary key of the database table. Now, I need to get the ID of the selected checkbox using JavaScript. I used a hidden field to store the ID of the row (The row is hidden and the user cannot see it on the display but you can see the value if you do the view source). Now, I like to access the hidden field of the selected row of the GridView.

<asp:TemplateField>

<ItemTemplate>

<asp:CheckBox id=”chkSelect” runat=”server” />

<asp:HiddenField ID=”hfID” runat=”server” Value='<%# Eval(“ID”) %>’ />

</ItemTemplate>

</asp:TemplateField>

And here is the JavaScript code:

function GetIDFromHiddenField()

{

var elements = document.getElementsByTagName(“INPUT”);

var ID;

var count = 0;

for(i=0; i< elements.length; i++)

{

if(elements[i].type == ‘checkbox’)

{

if(elements[i].checked == true)

{

count = count + 1;

ID= elements[i].nextSibling.nextSibling.value;

}

}

}

// check if more then one exam is selected. If so, then alert the user

if(count > 1) { alert(‘Please only select a single item from the list’); return (-1); }

else return ID;

}

Althought I am only allowing the user to select a single item I am sure you got the basic idea.

Show all GridView Rows in EditMod

(from: http://aspadvice.com/blogs/azamsharp/archive/2006/11/08/Show-all-GridView-Rows-in-EditMode.aspx)

Sometimes, in the application we have a requirement that you need to show the GridView rows in edit mode. This means that all the rows will contain textboxes and the data should be present in the textboxes. Once, you are done with editing you can update and get back to the view mode. In this post I will simply show you how to change the mode of the GridView from view to edit. I will not be using any datasource controls.

The first task is the create a GridView. Check out the html code to create the GridView control:

<asp:GridView ID=”gvUsers” AutoGenerateColumns=”false” runat=”server” OnRowDataBound=”gvUsers_RowDataBound”>

<Columns>

<asp:TemplateField HeaderText=”User ID”>

<ItemTemplate>

<asp:Label ID=”lblUserID” runat=”server” Text=’<%# Eval(“UserID”) %> />

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText=”First Name”>

<ItemTemplate>

<asp:Label ID=”lblFirstName” Visible=’<%# !(bool) IsInEditMode %> runat=”server” Text=’<%# Eval(“FirstName”) %> />

<asp:TextBox ID=”txtFirstName” Visible=’<%# IsInEditMode %> runat=”server” Text=’<%# Eval(“FirstName”) %> />

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText=”Last Name”>

<ItemTemplate>

<asp:Label ID=”lblLastName” Visible=’<%# !(bool) IsInEditMode %> runat=”server” Text=’<%# Eval(“LastName”) %> />

<asp:TextBox ID=”txtLastName” Visible=’<%# IsInEditMode %> runat=”server” Text=’<%# Eval(“LastName”) %> />

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

Check out the screen shot below:

GridViewAllRowsEditMode1

As, you can see in the html code that both my label and the textbox are in the ItemTemplate and there visibility depends on the IsInEditMode property. Now, let’s check out the code behind:

private bool isEditMode = false;

protected void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

{

BindData();

}

}

private void BindData()

{

string connectionString = “Server=localhost;Database=School;Trusted_Connection=true”;

SqlConnection myConnection = new SqlConnection(connectionString);

SqlDataAdapter ad = new SqlDataAdapter(“SELECT UserID, FirstName, LastName FROM Users”, myConnection);

DataSet ds = new DataSet();

ad.Fill(ds);

gvUsers.DataSource = ds;

gvUsers.DataBind();

}

// This method will put the GridView in the edit mode

protected void Button1_Click(object sender, EventArgs e)

{

isEditMode = true;

BindData();

}

protected bool IsInEditMode

{

get { return this.isEditMode; }

set { this.isEditMode = value; }

}

protected void Button2_Click(object sender, EventArgs e)

{

isEditMode = false;

BindData();

}

When the button is clicked I simply change the isEditMode to true or depending depending that if I want to view the GridView in edit mode or view mode. Check out the effect below:

SQL : ntext, text,image field

Transact-SQL Reference
ntext, text, and image

Fixed and variable-length data types for storing large non-Unicode and Unicode character and binary data. Unicode data uses the UNICODE UCS-2 character set.

ntext

Variable-length Unicode data with a maximum length of 230 – 1 (1,073,741,823) characters. Storage size, in bytes, is two times the number of characters entered. The SQL-92 synonym for ntext is national text.

text

Variable-length non-Unicode data in the code page of the server and with a maximum length of 231-1 (2,147,483,647) characters. When the server code page uses double-byte characters, the storage is still 2,147,483,647 bytes. Depending on the character string, the storage size may be less than 2,147,483,647 bytes.

image

Variable-length binary data from 0 through 231-1 (2,147,483,647) bytes.

Remarks

These functions and statements can be used with ntext, text, or image data.

Functions Statements
DATALENGTH READTEXT
PATINDEX SET TEXTSIZE
SUBSTRING UPDATETEXT
TEXTPTR WRITETEXT
TEXTVALID

Godaddy share hosting doesn’t support CSK 2 ?

CSK 2.0 , Commerce Starter Kit —

The PayPal-enabled Commerce Starter Kit is a free, open source e-commerce storefront written in C# specifically for ASP.NET 2.0. It features out-of-the-box product catalog and shopping cart functionality that allows web developers to setup, run, and maintain an online store with little or no costs, license fees, or limitations. Some assembly required.

http://pdn.paypal.com/commercestarterkit/default.htm

It is a good open source e-commercial package for those people want to open their online stores.

But, there is a very important problem: Does your hosing support CSK 2.0?

check here:  http://forums.commercestarterkit.org/

How To Push Your Site Live

If you need some help putting the CSK on your web host’s server, here’s a walkthrough. It’s important to note that the CSK only works in Full Trust. Most ISPs will only allow .NET 2.0 Web sites to run in Partial Trust (aka Medium Trust). This won’t allow the CSK to make Web Service calls to PayPal (or the gateway of your choice) so please make sure you ask your ISP if they will support full trust.

I heard Godaddy.com’s share hosting maybe don’t have something that CSK needs: GoDaddy locks down all sites under medium trust which does not allow the PayPal API to execute, thus disabling the site (http://forums.commercestarterkit.org/forums/1/207/ShowThread.aspx ), but you also see the information seems Godaddy and MS are doing sth. to resolve this problem.

Just now I have send my question about this to Godaddy’s support team. We just see what they will reply to me.

Result: Godaddy response their share hosting only medium trust just like most of ISP.

Finally, I found info that maybe CSK 2.0 can use Medium Trust hosting for Paypal standard edition not paypal pro, that means if you don’t set Paypal pro payment method just Paypal standard, it can work well.

http://forums.commercestarterkit.org/forums/thread/9010.aspx

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