Tuesday, August 9, 2011
System.Collections.Generic Namespace ()
"System.Collections.Generic Namespace ()" ( http://bit.ly/qqtEH3 )
Using Classes and Structures in Visual Basic .NET
"Using Classes and Structures in Visual Basic .NET" ( http://bit.ly/n4jVjJ )
Labels:
Class,
Link,
MSDN,
Reference Types,
Storage,
Structures,
Value Types
Value Types and Reference Types
"Value Types and Reference Types" ( http://bit.ly/r2mnZE )
Tuesday, May 10, 2011
EXCEL VBA TOC
Sub CreateTOC()
' Code by Zack Baresse
If ActiveWorkbook Is Nothing Then
MsgBox "You must have a workbook open first!", vbInformation, "No Open Book"
Exit Sub
End If
With Application
.ScreenUpdating = False
.DisplayAlerts = False
Dim ws As Worksheet, _
ct As Chart, _
shtName As String, _
nrow As Long, _
tmpCount As Long, _
i As Long, _
numCharts As Long
nrow = 3
i = 1
numCharts = ActiveWorkbook.Charts.Count
On Error GoTo hasSheet
Sheets("Table of Contents").Activate
If MsgBox("You already have a Table of Contents page. Would you like to overwrite it?", _
vbYesNo + vbQuestion, "Replace TOC page?") = vbYes Then GoTo createNew
Exit Sub
hasSheet:
Sheets.Add Before:=Sheets(1)
GoTo hasNew
createNew:
Sheets("Table of Contents").Delete
GoTo hasSheet
hasNew:
tmpCount = ActiveWorkbook.Charts.Count
If tmpCount > 0 Then tmpCount = 1
ActiveSheet.Name = "Table of Contents"
With Sheets("Table of Contents")
'.Cells.Interior.ColorIndex = 4
With .Range("B2")
.Value = "Table of Contents"
.Font.Bold = True
.Font.Name = "Calibri"
.Font.Size = "24"
End With
End With
For Each ws In ActiveWorkbook.Worksheets
nrow = nrow + 1
With ws
shtName = ws.Name
With Sheets("Table of Contents")
.Range("B" & nrow).Value = nrow - 3
.Range("C" & nrow).Hyperlinks.Add _
Anchor:=Sheets("Table of Contents").Range("C" & nrow), Address:="#'" & _
shtName & "'!A1", TextToDisplay:=shtName
.Range("C" & nrow).HorizontalAlignment = xlLeft
End With
End With
Next ws
If numCharts <> 0 Then
For Each ct In ActiveWorkbook.Charts
nrow = nrow + 1
shtName = ct.Name
With Sheets("Table of Contents")
.Range("B" & nrow).Value = nrow - 3
.Range("C" & nrow).Value = shtName
.Range("C" & nrow).HorizontalAlignment = xlLeft
End With
Next ct
End If
With Sheets("Table of Contents")
With .Range("B2:G2")
.MergeCells = True
.HorizontalAlignment = xlLeft
End With
With .Range("C:C")
.EntireColumn.AutoFit
.Activate
End With
.Range("B4").Select
End With
.DisplayAlerts = True
.ScreenUpdating = True
End With
MsgBox "Done!" & vbNewLine & vbNewLine & "Please note: " & _
"Charts are listed after regular " & vbCrLf & _
"worksheets and will not have hyperlinks.", vbInformation, "Complete!"
End Sub
' Code by Zack Baresse
If ActiveWorkbook Is Nothing Then
MsgBox "You must have a workbook open first!", vbInformation, "No Open Book"
Exit Sub
End If
With Application
.ScreenUpdating = False
.DisplayAlerts = False
Dim ws As Worksheet, _
ct As Chart, _
shtName As String, _
nrow As Long, _
tmpCount As Long, _
i As Long, _
numCharts As Long
nrow = 3
i = 1
numCharts = ActiveWorkbook.Charts.Count
On Error GoTo hasSheet
Sheets("Table of Contents").Activate
If MsgBox("You already have a Table of Contents page. Would you like to overwrite it?", _
vbYesNo + vbQuestion, "Replace TOC page?") = vbYes Then GoTo createNew
Exit Sub
hasSheet:
Sheets.Add Before:=Sheets(1)
GoTo hasNew
createNew:
Sheets("Table of Contents").Delete
GoTo hasSheet
hasNew:
tmpCount = ActiveWorkbook.Charts.Count
If tmpCount > 0 Then tmpCount = 1
ActiveSheet.Name = "Table of Contents"
With Sheets("Table of Contents")
'.Cells.Interior.ColorIndex = 4
With .Range("B2")
.Value = "Table of Contents"
.Font.Bold = True
.Font.Name = "Calibri"
.Font.Size = "24"
End With
End With
For Each ws In ActiveWorkbook.Worksheets
nrow = nrow + 1
With ws
shtName = ws.Name
With Sheets("Table of Contents")
.Range("B" & nrow).Value = nrow - 3
.Range("C" & nrow).Hyperlinks.Add _
Anchor:=Sheets("Table of Contents").Range("C" & nrow), Address:="#'" & _
shtName & "'!A1", TextToDisplay:=shtName
.Range("C" & nrow).HorizontalAlignment = xlLeft
End With
End With
Next ws
If numCharts <> 0 Then
For Each ct In ActiveWorkbook.Charts
nrow = nrow + 1
shtName = ct.Name
With Sheets("Table of Contents")
.Range("B" & nrow).Value = nrow - 3
.Range("C" & nrow).Value = shtName
.Range("C" & nrow).HorizontalAlignment = xlLeft
End With
Next ct
End If
With Sheets("Table of Contents")
With .Range("B2:G2")
.MergeCells = True
.HorizontalAlignment = xlLeft
End With
With .Range("C:C")
.EntireColumn.AutoFit
.Activate
End With
.Range("B4").Select
End With
.DisplayAlerts = True
.ScreenUpdating = True
End With
MsgBox "Done!" & vbNewLine & vbNewLine & "Please note: " & _
"Charts are listed after regular " & vbCrLf & _
"worksheets and will not have hyperlinks.", vbInformation, "Complete!"
End Sub
Tuesday, April 26, 2011
Gridview DataBound Event
This event fires once the Gridview has finished Databinding - that is, the Gridview has been populated with all of the data on the Datasource.
Don't get it mixed up with RowDataBound event which fires after each row has finished binding.
This is a great place to run any code that needs to wait until the Gridview is finished binding - perhaps we have been accumulating the values in each row, as they bind & wish to write them out at the end.
"BaseDataBoundControl.DataBound Event (System.Web.UI.WebControls)" ( http://bit.ly/gXWo3S )
Don't get it mixed up with RowDataBound event which fires after each row has finished binding.
This is a great place to run any code that needs to wait until the Gridview is finished binding - perhaps we have been accumulating the values in each row, as they bind & wish to write them out at the end.
"BaseDataBoundControl.DataBound Event (System.Web.UI.WebControls)" ( http://bit.ly/gXWo3S )
Labels:
ASP.NET,
databinding,
Databound,
DataSource,
Gridview,
Link,
MSDN
Finding controls in the GridView
Because a GridView renders out multiple rows, each of them contain controls with identical names. Finding the right control requires a trick.
For instance, in the RowDataBound/DataBound event, if we were looking for a particular label so that we could write a value to it 'on the fly', we would use the following code:
The CTYPE function is a conversion function. In this case, it will return all of the data associated with the label we are trying to locate, as a Label object. Once located, we can manipulate this particular instance.
For instance, in the RowDataBound/DataBound event, if we were looking for a particular label so that we could write a value to it 'on the fly', we would use the following code:
Dim lblItemotal As Label = CType(e.Row.FindControl("lblItemTotal"), Label)
The CTYPE function is a conversion function. In this case, it will return all of the data associated with the label we are trying to locate, as a Label object. Once located, we can manipulate this particular instance.
Labels:
ASP.NET,
Conversion,
CTYPE,
Databound,
e,
FindControl,
Gridview,
Link,
MSDN,
row
GridView TemplateField
The Gridview allows you to add a number of different types of fields.
The TemplateField allows more flexibility in that you can customize the field to a greater degree.
In the example source above, a TemplateField has been used in the Gridview to include an ImageButton. This is a good result, as by default, an ImageButton cannot be included.
This ImageButton has its CommandName property set to 'Increase' and it's CommandArgument property set to the 'CartID' field on the Datasource (the list the gridview is bound to). It also has an ImageURL which is the path to the image to be displayed on the button.
Here is the view of the Gridview fields from within the Edit Column dialogue. There are a total of 4 templateFields used in this example - Total, Increase, Decrease & Remove. Notice that the TemplateFields have a slightly different icon.
In order to edit the contents of the TemplateField, you will need to select the 'Edit Templates' option from the Gridview tasks menu.
Select the template you wish to edit and it will open out for you.
You will notice there are several regions in the template, in this example, I have placed an ImageButton in the ItemTemplate.
Once you have named the control (via the normal Properties pane) and set the ImageURL, open the Tasks menu and select 'Edit DataBindings'.
There are a number of settings we can play with here.
Select the CommandArgument property from the 'Bindable Properties' list and type 'Bind', followed in parenthesis by the field on the datasource to bind.
Check the 'Show all properties' box and now select the CommandName property from the 'Bindable Properties' list and type a name for the command.
Click OK and then from the Gridview tasks menu, select 'End template editing'.
The image below shows the rendered out Gridview.
When the 'Increase' button is clicked in the Gridview, this causes the RowCommand event of the Gridview to fire.
The CommandName string & CommandArgument value are passed to this event for further processing:
Remember that in this example, the CommandName string is 'Increase' & the CommandArgument is holding the CartID.
One thing you see often in this example is the use of 'e'. If you take a look at the parameter list for the event, you can see that the 2nd parameter is called 'e'.
'e' represents a collection of values that hold information about the state of the gridview - including which button was clicked and any CommandName and CommandArgument properties.
As you can see, the first thing happening in this code is the getting of the CartID from the CommandArgument. This is stored in an integer variable.
The next thing you will notice are a series of If statements to determine what the CommandName of the button was. From there, the appropriate code is executed and the CartID is passed along.
The TemplateField allows more flexibility in that you can customize the field to a greater degree.
In the example source above, a TemplateField has been used in the Gridview to include an ImageButton. This is a good result, as by default, an ImageButton cannot be included.
This ImageButton has its CommandName property set to 'Increase' and it's CommandArgument property set to the 'CartID' field on the Datasource (the list the gridview is bound to). It also has an ImageURL which is the path to the image to be displayed on the button.
Here is the view of the Gridview fields from within the Edit Column dialogue. There are a total of 4 templateFields used in this example - Total, Increase, Decrease & Remove. Notice that the TemplateFields have a slightly different icon.
In order to edit the contents of the TemplateField, you will need to select the 'Edit Templates' option from the Gridview tasks menu.
Select the template you wish to edit and it will open out for you.
You will notice there are several regions in the template, in this example, I have placed an ImageButton in the ItemTemplate.
Once you have named the control (via the normal Properties pane) and set the ImageURL, open the Tasks menu and select 'Edit DataBindings'.
There are a number of settings we can play with here.
Select the CommandArgument property from the 'Bindable Properties' list and type 'Bind', followed in parenthesis by the field on the datasource to bind.
Check the 'Show all properties' box and now select the CommandName property from the 'Bindable Properties' list and type a name for the command.
Click OK and then from the Gridview tasks menu, select 'End template editing'.
The image below shows the rendered out Gridview.
When the 'Increase' button is clicked in the Gridview, this causes the RowCommand event of the Gridview to fire.
The CommandName string & CommandArgument value are passed to this event for further processing:
Remember that in this example, the CommandName string is 'Increase' & the CommandArgument is holding the CartID.
One thing you see often in this example is the use of 'e'. If you take a look at the parameter list for the event, you can see that the 2nd parameter is called 'e'.
'e' represents a collection of values that hold information about the state of the gridview - including which button was clicked and any CommandName and CommandArgument properties.
As you can see, the first thing happening in this code is the getting of the CartID from the CommandArgument. This is stored in an integer variable.
The next thing you will notice are a series of If statements to determine what the CommandName of the button was. From there, the appropriate code is executed and the CartID is passed along.
Labels:
ASP.NET,
CommandArgument,
CommandName,
e,
Gridview,
ImageButton,
ImageURL,
Link,
MSDN,
RowCommand,
TemplateField
ImageButton Class
"ImageButton Class (System.Web.UI.WebControls)" ( http://bit.ly/hguk2A )
Properties of note:
ImageURL: Gets or sets the URL that provides the path to an image to display
CommandArgument: Specify a value that can be programmatically read by onCommand event handlers - such as the Gridview. Think, passing a value to a parameter. Optional.
CommandName: Specify a string that can be programmatically identified by onCommand event handlers - such as the Gridview RowCommand event. Optional
Properties of note:
ImageURL: Gets or sets the URL that provides the path to an image to display
CommandArgument: Specify a value that can be programmatically read by onCommand event handlers - such as the Gridview. Think, passing a value to a parameter. Optional.
CommandName: Specify a string that can be programmatically identified by onCommand event handlers - such as the Gridview RowCommand event. Optional
Labels:
ASP.NET,
CommandArgument,
CommandName,
Gridview,
ImageButton,
ImageURL,
Link,
MSDN
FormatCurrency Function
To format a decimal value as currency for output:
Also see: Format currency in GridView
lblLabel.Text = FormatCurrency(decPrice)
Also see: Format currency in GridView
Databiding a GridView
A gridview can 'databind' to any collection/list of objects.
Properties of note:
DataSource - the collection to bind to
DataKeyNames - an array of the field on the datasource to use as the key/identifier (often the Primary Key, in the case of database results). Optional.
Databind - causes the Gridview to bind with the datasource - starts executing other events such as RowDataBound, etc.
In the example above, the getCart method of the myModel object, returns a list. The CartID feild is used as the DataKeyName.
Properties of note:
DataSource - the collection to bind to
DataKeyNames - an array of the field on the datasource to use as the key/identifier (often the Primary Key, in the case of database results). Optional.
Databind - causes the Gridview to bind with the datasource - starts executing other events such as RowDataBound, etc.
Dim myModel As New ModelFacade
gvShoppingCart.DataSource = myModel.getCart()
gvShoppingCart.DataKeyNames = New String() {"CartID"}
gvShoppingCart.DataBind()In the example above, the getCart method of the myModel object, returns a list. The CartID feild is used as the DataKeyName.
Calculating GST
To calculate how much GST to add: Multiply by 0.1
To add GST to arrive at a total price: Multiply by 1.1
To calculate how much GST is included in a price: Divide by 11
To calculate how much the price was before GST: Divide by 1.1
decSubTotal = decSubTotal / 1.1
From "Calculate GST in the Blink of an Eye - For Dummies" ( http://bit.ly/efOjUP )
decGST = decSubTotal * 0.1
To add GST to arrive at a total price: Multiply by 1.1
decTotalPrice = decSubTotal * 1.1
To calculate how much GST is included in a price: Divide by 11
decGST = decTotalPrice / 11
To calculate how much the price was before GST: Divide by 1.1
decSubTotal = decSubTotal / 1.1
From "Calculate GST in the Blink of an Eye - For Dummies" ( http://bit.ly/efOjUP )
DataRowView Class
"DataRowView Class (System.Data)" ( http://bit.ly/dLuGGk )
Represents a customized view of a DataRow.
Here's a kitteh to relax you...
Back to the story!
For instance, in the RowDataBound event of a GridView, where a single row/record of data is bound, we can create a view of the data on the row by declaring a DataRowView object & assigning the DataItem property of the row to that object. From there, we are free to pick out the items on the row that are of interest to us.
Represents a customized view of a DataRow.
Here's a kitteh to relax you...
Back to the story!
For instance, in the RowDataBound event of a GridView, where a single row/record of data is bound, we can create a view of the data on the row by declaring a DataRowView object & assigning the DataItem property of the row to that object. From there, we are free to pick out the items on the row that are of interest to us.
' Get a view of the data bound to the current row.
Dim drvCurrentDataRow As DataRowView = e.Row.DataItem
' Get the price field from the row.
Dim decPrice As Decimal = drvCurrentDataRow("Price")
' Get the quantity field from the row.
Dim intQuantity As Integer = drvCurrentDataRow("Quantity")
GridView RowDataBound Event
Occurs when a data row is bound to data in a GridView control.
This event will fire for as many times as there are rows on the datasource. This means 50 database results = 50 rows = 50 RowDataBound event fires.
If you need to access controls/values on a particular row, you can use the FindControl method within this event.
"GridView.RowDataBound Event (System.Web.UI.WebControls)" ( http://bit.ly/fVE5bo )
This event will fire for as many times as there are rows on the datasource. This means 50 database results = 50 rows = 50 RowDataBound event fires.
If you need to access controls/values on a particular row, you can use the FindControl method within this event.
"GridView.RowDataBound Event (System.Web.UI.WebControls)" ( http://bit.ly/fVE5bo )
Gridview RowCommand Event
Occurs when a button is clicked in a GridView control.
"GridView.RowCommand Event (System.Web.UI.WebControls)" ( http://bit.ly/ehstPZ )
"GridView.RowCommand Event (System.Web.UI.WebControls)" ( http://bit.ly/ehstPZ )
SQL INNER JOIN Keyword
The INNER JOIN keyword return rows when there is at least one match in both tables.
"SQL INNER JOIN Keyword" ( http://bit.ly/gAwOax )
"SQL INNER JOIN Keyword" ( http://bit.ly/gAwOax )
Monday, April 25, 2011
GridView ListItemType
"ListItemType Enumeration (System.Web.UI.WebControls)" ( http://bit.ly/fdd34j )
GridView DataControlRowType
"DataControlRowType Enumeration (System.Web.UI.WebControls)" ( http://bit.ly/fA1sJ6 )
There are several different row types in a Gridview, each with its own function. When using an event such as RowDataBound (where individual rows are of interest to us), it is important to check for the DataControlRowType.
We can do so. The following example checks for a DataRow (a normal row of data):
End If
There are several different row types in a Gridview, each with its own function. When using an event such as RowDataBound (where individual rows are of interest to us), it is important to check for the DataControlRowType.
- Header
- Footer
- DataRow
- Separator
- Pager
- EmptyDataRow
We can do so. The following example checks for a DataRow (a normal row of data):
If e.Row.RowType = DataControlRowType.DataRow Then
' Code...
Labels:
ASP.NET,
DataControlRowType,
DataRow,
EmptyDataRow,
Footer,
Gridview,
Header,
If Statement,
Link,
MSDN,
Pager,
Separator
GridView
"GridView Class (System.Web.UI.WebControls)" ( http://bit.ly/gbHIyh )
GridView RowState Property
"GridViewRow.RowState Property (System.Web.UI.WebControls)" ( http://bit.ly/fh3x0j )
GridView RowType Property
"GridViewRow.RowType Property (System.Web.UI.WebControls)" ( http://bit.ly/h4fyeP )
Monday, April 18, 2011
Introduction to Exception Handling in Visual Basic .NET
"Summary: This article provides an overview of structured and unstructured exception handling in Visual Basic .NET. It includes considerations that help you choose the right exception-handling alternative, the approaches involved in each alternative, how to create your own exceptions, and the exception object's properties. A table at the end lists the predefined exception classes and their derived classes."
from http://msdn.microsoft.com/en-us/library/aa289505(v=vs.71).aspx
from http://msdn.microsoft.com/en-us/library/aa289505(v=vs.71).aspx
Loop through a DataSet
Dim dr As DataRow
Dim dt As DataTable
dt = DataSetName.Tables(0)
For Each dr In dt.Rows
something = dr("FeildName")
Next
Dim dt As DataTable
dt = DataSetName.Tables(0)
For Each dr In dt.Rows
something = dr("FeildName")
Next
Sunday, April 17, 2011
Argument Passing ByVal and ByRef
"In Visual Basic, you can pass an argument to a procedure by value or by reference by specifying the ByVal or ByRef keywords, respectively. Passing an argument by value means the procedure cannot modify the contents of the variable element in the calling code underlying the argument. Passing by reference allows the procedure to modify the contents in the same way that the calling code itself can."
From http://msdn.microsoft.com/en-us/library/ddck1z30(v=vs.71).aspx
From http://msdn.microsoft.com/en-us/library/ddck1z30(v=vs.71).aspx
Labels:
Arguments,
ByRef,
ByVal,
Link,
MSDN,
Parameters,
Procedures,
Visual Basic
Parameter Arrays
"Usually, you cannot call a procedure with more arguments than the procedure declaration specifies. When you need an indefinite number of arguments, you can declare a parameter array, which allows a procedure to accept an array of values for a parameter. You do not have to know the number of elements in the parameter array when you define the procedure. The array size is determined individually by each call to the procedure."
From http://msdn.microsoft.com/en-us/library/538f81ec%28v=VS.100%29.aspx
From http://msdn.microsoft.com/en-us/library/538f81ec%28v=VS.100%29.aspx
Labels:
Array,
Link,
MSDN,
ParameterArray,
Parameters,
Visual Basic
Return ID from row insert - SCOPE IDENTITY
"INSERT INTO TableName(FeildName, FeildName) VALUES (Value, Value); SELECT IDColumnName FROM TableName WHERE (IDColumnName = SCOPE_IDENTITY())"
intID = CommandObject.ExecuteScalar
http://msdn.microsoft.com/en-us/library/ms190315.aspx
intID = CommandObject.ExecuteScalar
http://msdn.microsoft.com/en-us/library/ms190315.aspx
Tuesday, April 5, 2011
Inserting into MS SQL Date data type
Literal string YYYY-MM-DD
"date (Transact-SQL)" ( http://bit.ly/gDqI2q )
"date (Transact-SQL)" ( http://bit.ly/gDqI2q )
Monday, March 21, 2011
Australian Area Codes
"Australian telephone area codes" ( http://bit.ly/fXitYB )
Sunday, March 20, 2011
Visual Basic Graphics & the Paint event
"Making Graphics Appear" ( http://bit.ly/dP9VNs )
Labels:
Draw,
Graphics,
Link,
MSDN,
Paint Event,
PaintEventArgs,
Visual Basic
Graphics & PaintEventArgs Class
"PaintEventArgs Class (System.Windows.Forms)" ( http://bit.ly/geBB61 )
Labels:
Draw,
Graphics,
Link,
MSDN,
PaintEventArgs,
Visual Basic
Tuesday, March 15, 2011
Truncate a text field in Gridview
Call a function from a control that supports databinding events (such as a label).
The example below truncates text where it is found to be greater than 50 in length and adds ... to the end.
The controls refers to a function in the backend by the name of TruncateString.
Source:
Code:
Protected Function TruncateString(ByVal TheText As String) As String
If TheText.Length > 50 Then
Return TheText.Substring(0, 50) & " ..."
Else
Return TheText
End If
End Function
The example below truncates text where it is found to be greater than 50 in length and adds ... to the end.
The controls refers to a function in the backend by the name of TruncateString.
Source:
<asp:TemplateField HeaderText="Desc2">
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# TruncateString(DataBinder.Eval(Container.DataItem,"Description").ToString()) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>Code:
Protected Function TruncateString(ByVal TheText As String) As String
If TheText.Length > 50 Then
Return TheText.Substring(0, 50) & " ..."
Else
Return TheText
End If
End Function
Monday, March 14, 2011
Hyperlinked image in Gridview
Method 1:
Works, however, it is difficult to format the dimensions of the image.
Source:
Use seperate Hyperlink control & Image controls - wrap the hyperlink tag around the image control.
Works, however, it is difficult to format the dimensions of the image.
Source:
<ItemTemplate>
<asp:HyperLink ID="HyperLink1"
runat="server"
ImageUrl='<%# Eval("ProductID", "ContentImages/{0}.jpg") %>'
NavigateUrl='<%# String.Format("~/productdetails.aspx?ProductID={0}", Eval("ProductID")) %>'>
</asp:HyperLink>
</ItemTemplate>
Method 2:
Use seperate Hyperlink control & Image controls - wrap the hyperlink tag around the image control.
<ItemTemplate>
<asp:HyperLink ID="hlkImageLink"
runat="server"
NavigateUrl='<%# String.Format("~/PT_productdetails.aspx?ProductID={0}", Eval("ProductID")) %>'>
<asp:Image ID="imgProductImage"
runat="server"
ImageUrl='<%# Eval("ProductID", "ContentImages/{0}.jpg") %>'
Width="50" Height="50" />
</asp:HyperLink>
</ItemTemplate>
Format currency in GridView
Set the DataFormatString property of the Gridview field to:
{0:C}
This will format the DataField at position 0 (in the array) to a currency value.
A decimal value of 99.0000 will be formatted to $99.00
Also see: FormatCurrency Function
{0:C}
This will format the DataField at position 0 (in the array) to a currency value.
A decimal value of 99.0000 will be formatted to $99.00
Also see: FormatCurrency Function
Tuesday, March 8, 2011
Referring to Connection String in Web.Config
When instantiating the SqlConnection object:
MyConnString = ConfigurationManager.ConnectionStrings("TheConnectionString").ConnectionString
Where "TheConnectionString" is the name of the connection string in Web.Config.
"SqlConnection Class (System.Data.SqlClient)" ( http://bit.ly/J5ew4y )
Monday, March 7, 2011
Detect Browser (Server side)
"How to determine browser type in server-side code without the BrowserType object in ASP.NET" ( http://bit.ly/hAAFXl )
lblUserAgent.Text = Request.Browser.Browser & " " & Request.Browser.Version
Saturday, March 5, 2011
Casting
"Cheat Sheet - Casting in VB.NET and C# - CodeProject" ( http://bit.ly/eNDEgR )
Wednesday, March 2, 2011
Server.Transfer Vs. Response.Redirect
STOP THE PRESS
"Server.Transfer Vs. Response.Redirect - Developer.com" ( http://bit.ly/e43UFS )
&
"Server.Transfer vs. Response.Redirect" ( http://bit.ly/h5uxCo )
"Server.Transfer Vs. Response.Redirect - Developer.com" ( http://bit.ly/e43UFS )
&
"Server.Transfer vs. Response.Redirect" ( http://bit.ly/h5uxCo )
Tuesday, March 1, 2011
Javascript comments
Javascript single line comment
//
Javascript multi-line comment
/*
This is a
multi line comment
*/
//
Javascript multi-line comment
/*
This is a
multi line comment
*/
StringBuilder Class
"StringBuilder Class (System.Text)" ( http://bit.ly/iidbFf )
EG:
"Iterate Through The Form Collection In ASP.NET 2.0 - Robert Robbins" ( http://bit.ly/gOFBQ0 )
EG:
"Iterate Through The Form Collection In ASP.NET 2.0 - Robert Robbins" ( http://bit.ly/gOFBQ0 )
Status codes in HTTP
"Status codes in HTTP" ( http://bit.ly/fgcm4q )
Sunday, February 6, 2011
Session Variables
Requests between servers and browsers are handled via HTTP - Hypertext Transfer Protocol.
HTTP is a stateless protocol. This means that each request is serviced as it comes; after the request is processed, all of the data is discarded. No state is maintained across requests even from the same client. In a nutshell, data from one page is generally unavailable on the next page etc.
When we create a Desktop Application, often we use variables to hold data that persists for the life of the program execution. There are several ways to achieve the same result on the ASP.NET platform. One way is to use Session Variables.
A Session Variable can be read from anywhere in your website. You can use them to store information for the lifetime of a single users visit. Session variables do not need to be declared, they can be written on the fly.
Session("SessionName") = value
That's not to say that we have stopped using variables, not at all. But in the ASP.NET environment we can no longer rely on them to store application wide data.
Checking the Session Exists
Sessions Time-out if the user is idle for a period of time. This period of time is variable from server to server but generally it is a matter of only a few minutes. Because of this, we should always check if the session exists before we attempt to reference one.
If Session.Item("CustomerID") IsNot Nothing Then
Response.Write(Session("CustomerID"))
Else
Response.Write("Session CustomerID does not exist")
End If
HTTP is a stateless protocol. This means that each request is serviced as it comes; after the request is processed, all of the data is discarded. No state is maintained across requests even from the same client. In a nutshell, data from one page is generally unavailable on the next page etc.
When we create a Desktop Application, often we use variables to hold data that persists for the life of the program execution. There are several ways to achieve the same result on the ASP.NET platform. One way is to use Session Variables.
A Session Variable can be read from anywhere in your website. You can use them to store information for the lifetime of a single users visit. Session variables do not need to be declared, they can be written on the fly.
Session("SessionName") = value
That's not to say that we have stopped using variables, not at all. But in the ASP.NET environment we can no longer rely on them to store application wide data.
Checking the Session Exists
Sessions Time-out if the user is idle for a period of time. This period of time is variable from server to server but generally it is a matter of only a few minutes. Because of this, we should always check if the session exists before we attempt to reference one.
If Session.Item("CustomerID") IsNot Nothing Then
Response.Write(Session("CustomerID"))
Else
Response.Write("Session CustomerID does not exist")
End If
Response, Request & Query Strings
Requests between servers and browsers are handled via HTTP - Hypertext Transfer Protocol.
HTTP is a stateless protocol. This means that each request is serviced as it comes; after the request is processed, all of the data is discarded. No state is maintained across requests even from the same client. In a nutshell, data from one page is generally unavailable on the next page etc.
Response is a property of the HttpResponse object. This represents the outgoing data from the current Web form object. We can use the Redirect method to navigate to a new Web form.
response.redirect("nextpage.aspx")
Request is a property of the HttpRequest object. This represents incoming data to the current Web form. The information stored in the Request object collections originates from the client
We can read the properties of the HttpRequest object to learn more about the client and the page currently being viewed.
Use Query Strings to send data to the next page
A Query String is composed of field-value pairs and is appended to a URL.
response.redirect("pagename.aspx?FieldName=Value")
The above URL contains a querystring containing a single name/value pair.
Here is another example:
response.redirect("pagename.aspx?FieldName1=Value1&FieldName2=Value2")
Query Strings are useful for passing non sensitive data between 2 pages. The querystring begins with the question mark (?) character. Each name value pair is delineated by an ampersand (&) character.
When using the concatenation character to build a querystring, you need to really pay attention to the ampersand as you are using it in 2 contexts:
1) as the delineator in the querystring
2) as the concatenation operator in the string as it is being built
For instance:
In the above querystring, there are 3 name/value pairs. Each value for each name, is supplied by a string variable. The string is built using the concatenation operator - the ampersand, however, each subsequent name/value pair is also separated by the ampersand character. Concentrate & you will be fine (see what I did there?). LOL.
Read Query Strings on the next page
We can use the request object to read the values of the fields within the Query String.
Dim X as String = Request.QueryString("FieldName")
or as per the above example:
Dim strFirstName as String = Request.QueryString("Firstname")
Dim strLastName as String = Request.QueryString("Lastname")
Dim strPostCode as String = Request.QueryString("PostCode")
The following series of screenshots show values from textboxes being concatenated into a querystring & then displayed on the following page:
1.
2.
3.
4.
5.
HTTP is a stateless protocol. This means that each request is serviced as it comes; after the request is processed, all of the data is discarded. No state is maintained across requests even from the same client. In a nutshell, data from one page is generally unavailable on the next page etc.
Response is a property of the HttpResponse object. This represents the outgoing data from the current Web form object. We can use the Redirect method to navigate to a new Web form.
response.redirect("nextpage.aspx")
Request is a property of the HttpRequest object. This represents incoming data to the current Web form. The information stored in the Request object collections originates from the client
We can read the properties of the HttpRequest object to learn more about the client and the page currently being viewed.
lblURL.Text = Request.Url.ToString
Use Query Strings to send data to the next page
A Query String is composed of field-value pairs and is appended to a URL.
response.redirect("pagename.aspx?FieldName=Value")
The above URL contains a querystring containing a single name/value pair.
Here is another example:
response.redirect("pagename.aspx?FieldName1=Value1&FieldName2=Value2")
Query Strings are useful for passing non sensitive data between 2 pages. The querystring begins with the question mark (?) character. Each name value pair is delineated by an ampersand (&) character.
When using the concatenation character to build a querystring, you need to really pay attention to the ampersand as you are using it in 2 contexts:
1) as the delineator in the querystring
2) as the concatenation operator in the string as it is being built
For instance:
In the above querystring, there are 3 name/value pairs. Each value for each name, is supplied by a string variable. The string is built using the concatenation operator - the ampersand, however, each subsequent name/value pair is also separated by the ampersand character. Concentrate & you will be fine (see what I did there?). LOL.
Read Query Strings on the next page
We can use the request object to read the values of the fields within the Query String.
Dim X as String = Request.QueryString("FieldName")
or as per the above example:
Dim strFirstName as String = Request.QueryString("Firstname")
Dim strLastName as String = Request.QueryString("Lastname")
Dim strPostCode as String = Request.QueryString("PostCode")
The following series of screenshots show values from textboxes being concatenated into a querystring & then displayed on the following page:
1.
Get a copy of the project here :))
Labels:
ASP.NET,
download code,
HTTP,
QueryString,
Request,
Response
global.asax
What is the Global.asax file?
Adding a global.asax file to your application allows your application to respond to application & session level events
Application level events
There are a number of application level events available in the global.asax file.
The Application_Start event is fired the first time when an application starts.
Application_Start
The Application_End event is last event of its kind that is fired when the application ends or times out. It typically contains application cleanup logic.
Application_End
Session level events
There are two session level events available in the global.asax file.
The Session_Start event is fired whenever a new session of the application starts.
Session_Start
The Session_End event is fired whenever a session with the application ends.
Session_End
Further reading:
MSDN: Global.asax file http://msdn.microsoft.com/en-us/library/1xaas8a2%28VS.71%29.aspx
Understanding the Global.asax file http://aspalliance.com/1114
StackOverflow: What are the Pros and Cons of using Global.asax? http://stackoverflow.com/questions/135661/what-are-the-pros-and-cons-of-using-global-asax
Cookies
What is a cookie?
Cookies are small text files that are added to a users browser by a web application to store session/user specific data. A web application is able to read the contents of a cookie(s) on each subsequent visit a user makes to a website.
Security considerations
Cookies are unsuitable for storing secure information such as passwords.
Adding a cookie
A cookie may contain a number of name/value pairs when it is added to the browser. The expiry date of a cookie defines how long the cookie should remain in the browser for.
Modifying a cookie
A cookie may be modified simply by overwriting it.
Removing a cookie
A cookie is removed by setting the expiry date to a time in the past.
Reading a cookie
After checking that a cookie exists, a cookie value may be read & used just like any other value.
Use the Request (outgoing) object to read a cookie.
Cookies are small text files that are added to a users browser by a web application to store session/user specific data. A web application is able to read the contents of a cookie(s) on each subsequent visit a user makes to a website.
Security considerations
Cookies are unsuitable for storing secure information such as passwords.
Adding a cookie
A cookie may contain a number of name/value pairs when it is added to the browser. The expiry date of a cookie defines how long the cookie should remain in the browser for.
Response.Cookies("userInfo")("userName") = "straximo"
Response.Cookies("userInfo")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(1)
Use the Response (outgoing) object to add a cookie.Response.Cookies("userInfo")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(1)
Modifying a cookie
A cookie may be modified simply by overwriting it.
Response.Cookies("userInfo")("userName") = "straximo4"
Response.Cookies("userInfo")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(1)
Use the Response (outgoing) object to modify a cookie.Response.Cookies("userInfo")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(1)
Removing a cookie
A cookie is removed by setting the expiry date to a time in the past.
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(-1)
Use the Response (outgoing) object to remove a cookie.Reading a cookie
After checking that a cookie exists, a cookie value may be read & used just like any other value.
If Not Request.Cookies("userInfo") Is Nothing Then
Label1.Text = Request.Cookies("userName")("userName")
Label2.Text = Request.Cookies("userName")("lastVisit")End If
Label1.Text = Request.Cookies("userName")("userName")
Label2.Text = Request.Cookies("userName")("lastVisit")End If
Use the Request (outgoing) object to read a cookie.
Multiple Constructors
What are multiple constructors?
A constructor is also a method and so it may also be overloaded.
eg. Constructor containing 3 parameters in the parameter list
End Class
A constructor is also a method and so it may also be overloaded.
eg. Constructor with an empty parameter list
End Class
eg. Constructor containing 2 parameters in the parameter list
End Class
Public Class User
Public Sub New()
' Code...
End Sub
' Code...
End Sub
End Class
eg. Constructor containing 2 parameters in the parameter list
Public Class User
Public Sub New(UserName As String, Password As String)
' Code...
End Sub
' Code...
End Sub
End Class
eg. Constructor containing 3 parameters in the parameter list
Public Class User
Public Sub New(UserName As String, Password As String, MembershipType As Membership)
' Code...
End Sub
' Code...
End Sub
End Class
Method Overloading
What is Method Overloading?
Method Overloading is a means to having multiple methods with the same name, but which have differing parameter lists. Also called 'Polymorphism' - one name, many forms.
Further reading:
Create Overloaded Methods in VB.NET http://www.devx.com/dotnet/Article/9303
Method Overloading http://en.wikipedia.org/wiki/Method_overloading
Method Overloading is a means to having multiple methods with the same name, but which have differing parameter lists. Also called 'Polymorphism' - one name, many forms.
eg. getUserName function with empty parameter list
eg. getUserName function with a single string parameter called UserID
eg. getUserName function with a string parameter called UserID & a Date parameter called MembershipDate
Public Function getUserName() As String
' Code...
Return Value
End Function
' Code...
Return Value
End Function
eg. getUserName function with a single string parameter called UserID
Public Function getUserName(UserID as Integer) As String
' Code...
Return Value
End Function
' Code...
Return Value
End Function
eg. getUserName function with a string parameter called UserID & a Date parameter called MembershipDate
Public Function getUserName(UserID As Integer, MembershipDate As Date) As String
' Code...
Return Value
End Function
' Code...
Return Value
End Function
Further reading:
Create Overloaded Methods in VB.NET http://www.devx.com/dotnet/Article/9303
Method Overloading http://en.wikipedia.org/wiki/Method_overloading
What is a page Postback?
When a Page Loads, it is either loading for the first time or it is loading again based on some kind of user interaction with that page. In the case of the latter, we call this a Postback.
How to avoid problems with Postback
You may have code in your load event that should only run the first time a page loads.
Each page contains a boolean property called IsPostback. This property can be checked at runtime to determine whether the page is loading for the first time or posting back to itself.
Use an If statement to determine the state of the Postback property.
Further reading:
MSDN: Page.IsPostback property http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
Debugging: Setting Breakpoints
What is a Breakpoint?
A breakpoint is a specified point in the program where program execution pauses. During this pause, the values of variables, parameters and other objects may be examined.
How do I set a Breakpoint?
Place your cursor in the margin of the code editor and double-click. You will now see a red bullet in the margin, this represents the breakpoint. Double-click to remove.
Run your project. When program execution reaches the breakpoint, the program will enter break mode. You will notice that the current breakpoint is highlighted with a yellow background.
While in break mode, use your mouse to hover over the names of variables, parameters and other objects to see the value they currently store.
If you have multiple break points, click the play button to reach each subsequent breakpoint.
Further reading:
MSDN: Debugging basics. Breakpoints http://msdn.microsoft.com/en-us/library/4607yxb0.aspx
Wikipedia: Breakpoints http://en.wikipedia.org/wiki/Breakpoint
A breakpoint is a specified point in the program where program execution pauses. During this pause, the values of variables, parameters and other objects may be examined.
How do I set a Breakpoint?
Place your cursor in the margin of the code editor and double-click. You will now see a red bullet in the margin, this represents the breakpoint. Double-click to remove.
Run your project. When program execution reaches the breakpoint, the program will enter break mode. You will notice that the current breakpoint is highlighted with a yellow background.
While in break mode, use your mouse to hover over the names of variables, parameters and other objects to see the value they currently store.
If you have multiple break points, click the play button to reach each subsequent breakpoint.
Further reading:
MSDN: Debugging basics. Breakpoints http://msdn.microsoft.com/en-us/library/4607yxb0.aspx
Wikipedia: Breakpoints http://en.wikipedia.org/wiki/Breakpoint
Page Tracing
What is page tracing?
Tracing allows you to view diagnostic information about a single request for an ASP.NET page.
Tracing allows you to view diagnostic information about a single request for an ASP.NET page.
Why use page tracing?
Page tracing is a handy way to see values such as session variables at run-time.
Further reading:
How to: Enable Tracing for an ASP.NET Page http://msdn.microsoft.com/en-us/library/94c55d08.aspx
MSDN: Reading ASP.NET trace information http://msdn.microsoft.com/en-us/library/kthye016%28VS.80%29.aspx
Wednesday, February 2, 2011
Console.Read Method
From "Console.Read Method (System)" ( http://bit.ly/g9pebT )
The Read method blocks its return while you type input characters; it terminates when you press the Enter key.
The Read method blocks its return while you type input characters; it terminates when you press the Enter key.
Pauses, slowing things down. System.Threading.Thread.Sleep
Accepts an argument specifying the length of the pause in milliseconds.
1 second = 1000 milliseconds
System.Threading.Thread.Sleep(5000)
1 second = 1000 milliseconds
System.Threading.Thread.Sleep(5000)
The difference between classes & modules
From "Classes vs. Modules" ( http://bit.ly/eEMVtk )
"The main difference between classes and modules is that classes can be instantiated as objects while standard modules cannot. Because there is only one copy of a standard module's data, when one part of your program changes a public variable in a standard module, any other part of the program gets the same value if it then reads that variable. In contrast, object data exists separately for each instantiated object. Another difference is that unlike standard modules, classes can implement interfaces..."
"The main difference between classes and modules is that classes can be instantiated as objects while standard modules cannot. Because there is only one copy of a standard module's data, when one part of your program changes a public variable in a standard module, any other part of the program gets the same value if it then reads that variable. In contrast, object data exists separately for each instantiated object. Another difference is that unlike standard modules, classes can implement interfaces..."
Thursday, January 13, 2011
Systems Development Lifecycle (SDLC): The Waterfall model
The Waterfall model is a traditional lifecycle that views a software project from beginning to end. Each step is well defined and generally has an end and start date.
For this reason, many iterative models have emerged - iterative, meaning repeating. An iterative model can be described as a servies of mini waterfalls that are repeated until the project is complete. Generally, each iteration will achieve a small area of the desired functionality.
- Requirements Definition
- Analysis
- Design
- Implementation
- Testing
For this reason, many iterative models have emerged - iterative, meaning repeating. An iterative model can be described as a servies of mini waterfalls that are repeated until the project is complete. Generally, each iteration will achieve a small area of the desired functionality.
Wednesday, January 12, 2011
Parts of an ASP.NET Web Application
Web Forms or .aspx pages
Web Forms and .aspx pages provide the user interface for the Web application.
Code-behind pages
Code-behind pages are associated with Web Forms and contain the server-side code for the Web Form.
Configuration Files
Configuration files are XML files that define the default settings for the Web application and the Web server. Every Web application has one Web.config configuration file.
Global.asax File
Global.asax files contain the needed code for responding to application-level events that are raised by ASP.NET.
XML Web service links
XML Web srevice links allow the Web application to send and recieve data from an XML Web service.
Database connectivity
Database connectivity allows the Web application to transfer data to and from database sources.
Caching
Caching allow the Web application to return Web Forms and data more quickly after the first request.
Web Forms and .aspx pages provide the user interface for the Web application.
Code-behind pages
Code-behind pages are associated with Web Forms and contain the server-side code for the Web Form.
Configuration Files
Configuration files are XML files that define the default settings for the Web application and the Web server. Every Web application has one Web.config configuration file.
Global.asax File
Global.asax files contain the needed code for responding to application-level events that are raised by ASP.NET.
XML Web service links
XML Web srevice links allow the Web application to send and recieve data from an XML Web service.
Database connectivity
Database connectivity allows the Web application to transfer data to and from database sources.
Caching
Caching allow the Web application to return Web Forms and data more quickly after the first request.
Subscribe to:
Posts (Atom)